Search This Blog

Monday, June 29, 2020

Modules in Python

Module Definition:-

A module is a Python file containing a set of functions and variables to be used in an application. It may also contain classes.

Example

 Let us consider we want to develop a calculator then we have to develop different modules as 

In above example calculator will contain different modules as Addition, subtraction, Multiply and division. All the module will contain different python code for a particular operation.

Why to use module?

  • We use modules to break down large programs into small manageable and organized files.
  • It provides re-usability of code.
  • The code in the modules can be reloaded and rerun as many times as needed.

How to call a module?

 We have to use the import keyword to incorporate the module into our program.When the Python interpreter encounters an import statement, it imports the module if it is present in the search path.
Syntaximport module1[,module2[,……,module]

Example 1: First create create a module named 'calculator.py'

def add(a, b):
    return (a+b)
def sub(a, b):
    return (a-b)
def div(a, b):
    return (a/b)
def mul(a, b):
    return (a*b)

Calling the above module
import calculator as md
res=md.sub(20,15)
print(res)
res=md.add(20,15)
print(res)
res=md.div(20,15)
print(res)
res=md.mul(20,15)
print(res)
Output:
5
35
1.33333333333333
300

Note 1: To use only one function we can import only one function by using from keyword as
Example 2:
from calculator import div
res=md.div(20,15)
Output:
1.33333333333

Note 2: To import all the functions of any module we can also use '*' symbol as
from calculator import *
res=md.div(20,15)
Output:
1.33333333333

Note 3: We can also rename the module by using as keyword as example 2.

Types of modules in Python

There are two types of module in Python as-

  • User defined module
  • Built- in module
1.User defined module
User defined modules are defined by developer as per their requirement.

2.Built-in module
Built in modules are written in C language and interpreted using the python interpreter.

help('modules') will give you the list of all the built-in modules in python.
Some example of built in module are-
  • math module
  • sample module
  • random module etc.