Python Modules – Complete Guide With Examples
A module in Python is a file that contains functions, classes, and variables which can be reused in other Python programs. Modules help in organizing code logically, making programs cleaner, structured, and easier to maintain.
Why Do We Use Modules?
- To reuse code across multiple files
- To keep programs clean and structured
- To group related functions into separate files
- To avoid rewriting the same logic again and again
- To make debugging easier
How a Module is Created?
In Python, a module is automatically created using the file name.
If you create a Python file named a.py, then Python treats a as a module.
# a.py
def fun1():
print("fun1")
def fun2():
print("fun2")
How to Import a Module in Another File?
To access the functions inside a.py from b.py, we use the import keyword.
# b.py
import a # importing module a.py
a.fun1()
a.fun2()
Explanation:
import aloads the filea.pyas module aa.fun1()calls the functionfun1inside modulea
Different Ways to Import Modules
1. Simple Import
import math
print(math.sqrt(25))
2. Import With Alias
Alias makes module name shorter.
import math as m
print(m.sqrt(36))
3. Import Specific Function
from math import sqrt
print(sqrt(49))
4. Import All Functions (Not Recommended)
from math import *
print(factorial(5))
Types of Python Modules
1. Built-in Modules
These come with Python installation:
- math – mathematical functions
- datetime – date & time
- random – random numbers
- os – operating system operations
- sys – system-level operations
2. User-Defined Modules
Created by the programmer (like a.py).
3. Third-Party Modules
Installed using pip:
pip install numpy
pip install pandas
pip install flask
Module Search Path in Python
When you import a module, Python searches for it in the following order:
- Current directory
- Python installed libraries
- External site-packages
import sys
print(sys.path)
Using __name__ == "__main__" in Modules
This is one of the most important concepts in modules. It is used to differentiate between:
- When a file is executed directly
- When a file is imported as a module
# a.py
def fun():
print("Function Called")
if __name__ == "__main__":
print("Running as main file")
fun()
# b.py
import a # this will NOT execute the main block of a.py
Why is this useful?
- Prevents unwanted execution when importing
- Makes module reusable
- Helps in testing code
Creating a Module With Multiple Categories of Functions
# calculator.py
def add(a, b):
return a + b
def sub(a, b):
return a - b
def multi(a, b):
return a * b
def div(a, b):
return a / b
Usage:
# main.py
import calculator as c
print(c.add(10, 20))
print(c.multi(5, 6))
Advanced Topic: Packages (Folder Modules)
What is a package?
A package is a folder containing multiple module files.
mypackage/
__init__.py
student.py
teacher.py
fees.py
Importing from packages:
from mypackage.student import getStudentData
from mypackage.teacher import getTeacherData
Benefits of Using Modules & Packages
- Enhances maintainability
- Improves code modularity
- Allows team-based development
- Reduces file sizes
- Improves debugging and testing
Practical Example – User Module for Student Record
# student.py
def getStudent(rno, name, branch):
print("Roll No:", rno)
print("Name:", name)
print("Branch:", branch)
# main.py
import student
student.getStudent(1001, "Manish", "CS")
Assignment – Practice Module Programs
- Create a Calculator module and import it into multiple files.
- Create a Student Management module with functions:
- addStudent()
- deleteStudent()
- updateStudent()
- Create a package bank containing:
- account.py
- loan.py
- customer.py
- Create a module for employee salary calculation.
- Create a login authentication module and call it from another file.
0 Comments
POST Answer of Questions and ASK to Doubt