A file with Python definitions and statements is known as a module. Variables, classes, and functions can all be defined in a module. Runnable code may also be included in a module. Code that has been grouped together into modules is simpler to read and use. Additionally, it organises the code logically.
Use of Module in Python:
The goal to create a module is to segment the code into distinct modules
with little to no interdependence between them.
Code that uses modules has fewer lines of code and can be reused more often
thanks to a single procedure. Additionally, it eliminates the need to
repeatedly write the same logic.
Since a whole team only works on a part or module of the entire code, using
modules also makes it easier to design programmes.
For example, Let's say you want to write a calculator programme.
Operations like addition, subtraction, multiplication, and division will be
present.
We can divide the code into distinct components or we can either make a
single module that performs all of these operations or individual modules
for each operation.
Create a Python Module:
To creat a module you have to save the code you want with the file extension .py.
Example 1
Save this code in a file named module.py
def add(x,y):
return(x+y)
def sub(x,y):
return(x-y)
def mul(x,y):
return(x*y)
def div(x,y):
return(x/y)
Use a Module:
Now, we are importing the module that we created earlier to perform operations.
Example
import module print(module.add(4,2)) print(module.sub(4,2)) print(module.mul(4,2)) print(module.sub(4,2))
Renaming module:
we can rename a module by using the keyword
as.
Example
import module as m print(m.add(4,2)) print(m.sub(4,2)) print(m.mul(4,2)) print(m.subt(4,2))
From import statement:
From statement helps us to import attributes from a module without
importing module as a whole.
Importing specific attributes:
from math import sqrt,factorial print(sqrt(9)) print(factorial(4))
Importing all attributes:
The * symbol used with the from import statement is used to import
all the names from a module.
from math import* print(sqrt(4)) print(factorial(3)) print(pi)




