Table of Contents
show
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
- Example:
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
Views: 1