In python module can be defined as a python program file which contains a python code including python functions, class, or variables. In other words, we can say that our python code file saved with the extension (.py) is treated as the module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the specific module.
# Python Module example
def sum(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
In the above example we have defined 4 functions sum(), sub(), mul() and div() inside a module named demo.
We need to load the module in our python code to use its functionality. Python provides two types of statements as defined below.
The import statement is used to import all the functionality of one module into another. Here, we must notice that we can use the functionality of any python source file by importing that file as the module into another python source file.
We can import multiple modules with a single import statement.
import module1,module2..
import demo #importing entire Module
a=int(input("Enter a :"))
b=int(input("Enter b :"))
print("Sum is :",demo.sum(a,b))
print("Sub is :",demo.sub(a,b))
print("Mul is :",demo.mul(a,b))
print("Div is :",demo.div(a,b))
Enter a :12
Enter b :6
Sum is : 18
Sub is : 6
Mul is : 72
Div is : 2.0
Instead of importing the whole module into the namespace, python provides the flexibility to import only the specific attributes of a module. This can be done by using from - import statement. In such case we don't use the dot operator.
Syntax:from module-name import *
from demo import *
a=int(input("Enter a :"))
b=int(input("Enter b :"))
print("Sum is :",sum(a,b))
print("Sub is :",sub(a,b))
print("Mul is :",mul(a,b))
print("Div is :",div(a,b))
Enter a :12
Enter b :6
Sum is : 18
Sub is : 6
Mul is : 72
Div is : 2.0
We can import specific function from a module without importing the module as a whole. Here is an example.
Syntax:from module-name import function1,function2…
from demo import sub,mul
#importing specific functionality from Module
a=int(input("Enter a :"))
b=int(input("Enter b :"))
print("Sub is :",sub(a,b))
print("Mul is :",mul(a,b))
Enter a :12
Enter b :6
Sub is : 6
Mul is : 72
Python provides us the flexibility to import some module with a specific name so that we can use this name to use that module in our python source file.
Syntax:import module-name as specific-name
import demo as c
a=int(input("Enter a :"))
b=int(input("Enter b :"))
print("Sum is :",c.sum(a,b))
print("Sub is :",c.sub(a,b))
Enter a :25
Enter b :12
Sum is : 37
Sub is : 13