Python Modules
Don't reinvent the wheel — import code from Python's huge standard library or from third-party packages.
Importing modules
Python
import math
import random
import datetime
math.sqrt(16) # 4.0
random.randint(1, 10) # random number 1-10
datetime.date.today() # today's date
Import specific names
Python
from math import sqrt, pi, floor
sqrt(25) # 5.0 — no "math." prefix needed
floor(4.9) # 4
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
Import with alias
Python
import numpy as np
import pandas as pd
arr = np.array([1, 2, 3])
df = pd.DataFrame({"a": [1,2]})
Essential standard library modules
| Module | What it does |
|---|---|
os | File system, environment variables, process control |
sys | Python interpreter, command-line args |
json | Parse and generate JSON |
re | Regular expressions |
datetime | Dates, times, timedeltas |
pathlib | File paths (modern, OOP approach) |
collections | Counter, defaultdict, deque, namedtuple |
itertools | Efficient iterators: product, combinations, chain |
random | Random numbers, sampling |
math | Math functions, constants |
csv | Read/write CSV files |
Create your own module
greetings.py
def hello(name):
return f"Hello, {name}!"
def goodbye(name):
return f"Goodbye, {name}!"
main.py
import greetings
print(greetings.hello("Raman")) # Hello, Raman!
pip — install third-party packages
Terminal
pip install requests # HTTP client
pip install pandas # data analysis
pip install numpy # numerical computing
pip install flask # web framework
pip install pytest # testing
pip list # see installed packages
pip freeze > requirements.txt # export for a project
Virtual environments
Always create a virtual environment per project so package versions don't conflict:
python -m venv venv then source venv/bin/activate (Mac/Linux) or venv\Scripts\activate (Windows).