Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Variables, Expression and...
  5. Modules

Modules

Definition

  • A module is a file consisting of python code. It can define functions, classes and variables and can also include runnable code
  • Any python file can be referenced as a module
  • A file containing python code, for example: test.py is called a module and its name would be test
  • Module vs. Function
    • Function: It’s a block of code that can be used or reused by calling it with a keyword.
    • Example: print () is a function
  • Module: It’s a .py file that contains a list of functions (it can also contain variables and classes).
    • Example: math.sqrt(a)
    • Where math is a module sqrt( ) is a function

Syntax

import module_name
module_name.function_name(variable)

Purpose

  • When the program grows more in the size, there is a need to split into several files for easier maintenance as well as re-usability of the code
  • Once the module is imported, functions or variables are referenced or used to the code

Types of Modules

  • Built in Module
  • Built in modules are written in C and integrated with python interpreter
  • Some important python modules are: math, random
  • User Defined Module

A module that is defined by the programmer. Any name can be given to a user defined module

Importing Built in Modules

import

It is simplest and most common way to use modules in the code

Example
import math
x = math.sqrt(25)
print("square root of 25 =",x)
Output
('square root of 25 =', 5.0)

from import

It is used to get a specific function in the code instead of complete file

Example
from math import pi
x = pi
print("value of pi is",x)
Output
('value of pi is', 3.141592653589793)

import with renaming

Creating an alias when importing a module using as

Example
import math as m
x = m.pi
print("value of pi is",x)
Output
 ('value of pi is', 3.141592653589793)

import all

To import all names (definitions) from a module using *

Example
from math import *
x = pi
print("value of pi is",x)
Output
('value of pi is', 3.141592653589793)

Creating User defined Module:

Step 1: To create a module, save the code in a file with extension .py

Example

def add(a,b):
    print(a+b)

Step 2: use the module just created using import statement

Example

import MyModule as mm
mm.add(5,1)

Output

6

Loading

Views: 1

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments