Modules in Python

  • A module is a collection of statements in which we store functions ,classes and variables.
  • Python module acts as a library in which we can store set of functions and can use as per our requirements.
  • Now i am going to create a module with name that contains a function add() that prints the sum of two given number.
#creating function
def add(x,y):
  • Now if we want to call add() function then we need to include this module in our python code.

  • There are two way of including module in our python code.
  • import statement
  • from import statement
  • Syntax:
    import module1,module2,........ module n  
  • We can import multiple modules in a single statements.
  • The import statements includes all the functionality of one module into another.
  • import keyword is used to include module.

#importing mymodule file
import mymodule
#taking user input
x=int(input("Enter first number:"))
y=int(input("Enter second number:"))
#calling function of mymodule
Enter first number:10
Enter second number:20
Sum= 30
  • This statement is used when there is a need to include only the specific attributes of a module.
  • Now i am going to create a new module that contains many functions.
def rectangle_area(h,w):
    return  h*w
def square_area(side):
    return  side*side
def circle_area(radius):
    return  2*3.14*radius
  • Now if we want to import only square_area() from the we should code like this
#importing square_area from
from geometry import square_area
side=int(input("Enter side of square:"))
#calling square_area
print("The area of Square:",square_area(side))
Enter side of square:12
The area of Square: 144
  • We can raname a module by using as keyword.
  • Syntax:
    import <old_module_name> as <new_module_name>

#Note:this line will include
#all the functions of
import  geometry as geo
side=int(input("Enter side of square:"))
#calling square_area
print("The area of Square:",geo.square_area(side))
Enter side of square:10
The area of Square: 100
  • It is a predefined function that returns list of all the functions or variables or sub-modules name defined in the given module.

import  geometry
['__builtins__', '__cached__', '__doc__', '__file__',
 '__loader__', '__name__', '__package__', '__spec__', 
 'circle_area', 'rectangle_area', 'square_area']
  • We can also define variables in module and can use in our python code.
import  variablemodule
#accessing module variables
Sum= 50 

Request:-If you found this post helpful then let me know by your comment and share it with your friend. 
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

If you have not subscribed my website then please subscribe my website. 

Try to learn something new and teach something new to other. Thanks.

Post a Comment