Modules, packages and environments
A module is any .py file; a package is a folder of modules. You reuse code with import. Third-party packages are installed from PyPI into a virtual environment — a private folder of packages for one project — with pip or the faster uv, and listed in pyproject.toml so anyone can recreate the setup.
Importing
import math
from datetime import date
from statistics import mean as average
import random
print(math.sqrt(16))
print(date(2026, 10, 1).strftime("%A"))
print(average([2, 4, 9]))
random.seed(1)
print(random.choice(["red", "green", "blue"]))4.0 Thursday 5 red
import math— use it asmath.sqrt(). Clear where each name comes from.from datetime import date— usedatedirectly. Good for names you use a lot.asrenames, e.g. the community standardimport pandas as pd.- Avoid
from module import *: you can't tell where names come from.
Writing your own module
VAT_RATE = 0.21
def with_vat(amount: float) -> float:
return round(amount * (1 + VAT_RATE), 2)
if __name__ == "__main__":
# runs only with: python pricing.py
print(with_vat(100))from pricing import with_vat
print(with_vat(50))$ python app.py
60.5
$ python pricing.py
121.0Packages
shop/
├── pyproject.toml
└── src/
└── shop/
├── __init__.py
├── pricing.py
└── orders.pyA folder with an __init__.py file is a package, imported with dots: from shop.pricing import with_vat. The src/ layout is the current recommendation because it stops you accidentally importing code that isn't installed.
Virtual environments
Each project needs its own versions of packages. A virtual environment is a folder (usually .venv) holding a private copy of Python's package directory, so projects can't break each other.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install requests
pip freeze > requirements.txtuv init shop
cd shop
uv add requests # creates .venv and updates pyproject.toml
uv run main.py # runs inside the environmentuv is a newer, very fast tool that installs Python versions, creates the environment and records dependencies in one step. Both approaches are fine; new projects increasingly use uv.
pyproject.toml
[project]
name = "shop"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
"requests>=2.32",
]pyproject.toml is the standard place for a project's name, Python version and dependencies. Commit it to git; never commit the .venv folder.
Practice
Use the standard library: import Counter from collections and mean from statistics. For rolls = [3, 6, 2, 6, 6, 1, 3], print the most common roll and how often it appears as a tuple, then the average roll rounded to 2 decimals.
(6, 3) 3.86