A module is a single Python file (.py
) that contains definitions (functions, variables, classes) you can use in other programs.
You can:
Create your own modules
Import built-in or third-party modules
import math
print(math.sqrt(16)) # Output: 4.0
A package is a collection of modules organized in directories that include a special __init__.py
file.
from datetime import datetime
print(datetime.now())
import math # Import whole module
from math import sqrt # Import specific function
import math as m # Import with alias
Module | Use Case |
---|---|
math |
Mathematical functions like sqrt , sin , etc. |
random |
Generate random numbers |
datetime |
Work with dates and time |
os |
Interact with the operating system |
sys |
Access system-specific parameters |
re |
Work with Regular Expressions |
json |
Handle JSON data |
statistics |
Mean, median, mode, etc. |
time |
Work with timestamps, delays |
collections |
Specialized container datatypes (Counter , deque ) |
itertools |
Tools for iterators (combinations , permutations ) |
functools |
Functional programming tools (reduce , lru_cache ) |
pip
)Package | Description |
---|---|
numpy |
Numerical computing |
pandas |
Data manipulation & analysis |
matplotlib |
Data visualization |
seaborn |
Statistical data visualization |
scikit-learn |
Machine learning tools |
tensorflow / torch |
Deep learning frameworks |
requests |
Send HTTP requests |
flask |
Lightweight web framework |
django |
High-level web framework |
openpyxl |
Excel file manipulation |
beautifulsoup4 |
Web scraping |
pytest |
Testing framework |
Create mymodule.py
:
def greet(name):
return f"Hello, {name}!"
Use in another file:
import mymodule
print(mymodule.greet("Abhi"))
my_package/
│
├── __init__.py
├── module1.py
└── module2.py
Use it like:
from my_package import module1
pip install numpy