Chapter 11 of 12
Modules let you organise code across files and reuse others' work through packages. The Python ecosystem (pip) is massive โ there's a library for almost everything you'll ever need.
# Built-in modules (no installation needed)
import os
import sys
import math
import random
import datetime
import json
import re
import pathlib
# Different import styles
import os # use as os.path.join(...)
import os.path # use as os.path.join(...)
from os import path, getcwd # use as path.join(...), getcwd()
from os.path import join, exists # use as join(...), exists(...)
import os as operating_system # alias
# Your own modules
from utils import format_date # from utils.py in the same folder
from utils.helpers import clean # from utils/helpers.py
math.sqrt(16) # 4.0
math.pi # 3.141592...
random.choice(["HTML", "CSS", "Python"]) # random item
random.randint(1, 100) # random integer# pip โ Python's package installer
pip install requests # install a package
pip install requests==2.28.1 # specific version
pip uninstall requests # remove a package
pip list # show installed packages
pip freeze > requirements.txt # export all installed packages
# requirements.txt โ the standard way to share dependencies
pip install -r requirements.txt # install from file
# Virtual environments โ isolated Python environments per project
python -m venv venv # create virtual env named 'venv'
source venv/bin/activate # activate (Mac/Linux)
venvScriptsactivate # activate (Windows)
deactivate # deactivate
# With venv active, pip installs only inside the project
pip install django
pip freeze > requirements.txt
# Add venv/ to .gitignore โ never commit it