Python allows you to organize large programs into reusable, manageable components using modules and packages.
A module is a Python file (.py) that contains variables, functions, and classes which can be reused in other programs.
# math_operations.py (module)
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Importing allows you to use code written in another module.
import math
print(math.sqrt(16))
import math as m
print(m.pi)
from math import sqrt
print(sqrt(25))
(Not recommended – pollutes namespace)
from math import *
print(pi)
Python provides many ready-to-use built-in modules.
import math
print(math.factorial(5))
print(math.ceil(4.3))
import random
print(random.randint(1, 10))
from datetime import datetime
print(datetime.now())
import os
print(os.getcwd())
import sys
print(sys.version)
You can create your own module by simply creating a .py file.
# calculator.py
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
import calculator
print(calculator.multiply(5, 4))
import calculator as calc
print(calc.divide(10, 2))
A package is a collection of related modules organized in folders.
mypackage/
│
├── __init__.py
├── math_utils.py
├── string_utils.py
# math_utils.py
def square(n):
return n * n
from mypackage.math_utils import square
print(square(6))
pip is used to install third-party libraries from PyPI.
pip install numpy
pip install pandas
pip uninstall numpy
pip list
A virtual environment creates an isolated Python environment for each project.
python -m venv venv
Windows
venv\Scripts\activate
Mac/Linux
source venv/bin/activate
requirements.txt lists all project dependencies.
pip freeze > requirements.txt
numpy==1.26.2
pandas==2.1.0
flask==3.0.0
pip install -r requirements.txt