⭐ Python Modules
A module in Python is simply a file that contains Python code — such as variables, functions, classes, and runnable code — that can be imported and reused in other Python programs.
A module helps in organizing large programs into small, manageable, and reusable code blocks.
⭐ Module Definition
A module is a Python file (.py) that contains definitions of functions, variables, and classes which can be reused in other programs.
In simple words:
👉 Module = A file containing Python code that can be imported
👉 Extension = .py
👉 Used for code reusability + modularity
⭐ Why Use Modules?
✔ Reusability of code
✔ Organize code into logical parts
✔ Avoid rewriting commonly used logic
✔ Easier to maintain large programs
✔ Provides namespaces (avoids name conflicts)
✔ Allows use of thousands of Python’s built-in modules
⭐ Examples of Modules in Python
Python comes with many built-in modules:
| Module | Purpose |
|---|---|
math | Mathematical functions |
random | Random number generation |
datetime | Date & time operations |
os | Operating system interaction |
sys | System-specific parameters |
statistics | Statistical operations |
⭐ Creating Your Own Module
Create a file named mymodule.py:
def greet(name):
return f"Hello, {name}!"
x = 100
Now import it in another Python file:
import mymodule
print(mymodule.greet("John"))
print(mymodule.x)
⭐ Importing Modules
Python provides many ways to import modules:
✔ 1. Basic import
import math
✔ 2. Import with alias
import math as m
print(m.sqrt(16))
✔ 3. Import specific functions
from math import sqrt, pi
✔ 4. Import all (not recommended)
from math import *
⭐ Module Search Path
When importing, Python looks for a module in:
- Current working directory
- Built-in modules
- Installed modules (site-packages)
- System environment paths
You can check this with:
import sys
print(sys.path)
⭐ Types of Modules
1. Built-in Modules
Provided with Python installation
Example: math, os, random
2. User-defined Modules
Modules written by the programmer
3. Third-party Modules
Installed using pip
Example: numpy, pandas, requests
⭐ Advantages of Modules
✔ Improves code reusability
✔ Keeps code organized
✔ Reduces program size
✔ Easy to debug and maintain
✔ Encourages modular programming
✔ Provides namespaces
⭐ Example Program Using Modules
Program using the math module:
import math
print(math.sqrt(25))
print(math.factorial(5))
print(math.pi)
⭐ Exam-ready Definition (Short)
A module in Python is a file containing Python definitions and statements.
It helps in organizing code logically and allows reuse of functions, variables, and classes by importing into other programs.
