Index
Module
A module in Python is simply a file that contains Python code — like functions, classes, or variables — that you can reuse in other programs.
✅ It helps keep code organized, readable, and reusable
✅ Example: Creating and Using a Module
1. Create a module (say in a file called mymath.py
):
# mymath.py
def add(a, b):
return a + b
def sub(a, b):
return a - b
2. Use this module in another file:
import mymath
print(mymath.add(5, 3)) # Output: 8
print(mymath.sub(5, 3)) # Output: 2
🧩 Built-in vs. User-defined Modules
Type | Example | Description |
---|---|---|
Built-in Module | math , random | Comes with Python |
User-defined | mymath , helper | Created by you or other developers |
🔹 Example: Using a Built-in Module
import math
print(math.sqrt(16)) # Output: 4.0
print(math.pi) # Output: 3.141592653589793
📦 Importing Modules – Options:
Syntax | Usage |
---|---|
import module_name | Import full module |
from module_name import func | Import specific function |
import module_name as short | Import module with alias |
✅ Example:
from math import sqrt
print(sqrt(25)) # Output: 5.0
import math as m
print(m.pi) # Output: 3.14159...
🎯 Why Use Modules?
- ✅ Reuse code
- ✅ Organize large programs
- ✅ Share code with others
- ✅ Avoid repeating yourself (DRY principle)
✅ Summary
Feature | Description |
---|---|
Module | A file containing Python code |
Use | To organize and reuse code |
Examples | math , random , your own files |