app.py source code compile → .pyc bytecode CPython VMruns bytecode output your toolbox venv · pip types · f-strings list · dict · set loops · comps def · try pathlib · class
PLATE 0 — From a text file to running code, and the tools you'll have by the last page.
A picture book for grown-ups · with code

How Python Works, and How to Write It Well

Fifteen spreads. Each one has a picture, the idea behind it, and real code you can paste into a terminal or a .py file.

Say it like a pro

"I keep each project in its own venv, type-hint my functions, use comprehensions and f-strings, model data with dataclasses, read files with pathlib inside a context manager, catch specific exceptions, and guard the entry point with __main__."

Every phrase in that sentence gets its own page. Use the tabs or the ← → keys.

System Python 3.12don't pip install here web-app/.venv data/.venv bot/.venv django 5.1requests 2.32 pandas 2.2numpy 2.1 discord.pyrequests 2.28 different versions of requests, no conflict each venv = its own python + its own site-packages
PLATE 1 — One project, one bubble. Nothing leaks between them.
Chapter 1 · Install & virtual environments

Set up like you've done it a hundred times

Install Python 3.12+ from python.org (on Windows, tick Add python.exe to PATH). Then give every project its own virtual environment, a private copy of Python with its own packages.

Terminal · check, create, activate
$ python --version
Python 3.12.4
$ mkdir my_project && cd my_project
$ python -m venv .venv
$ .venv\Scripts\activate          # Windows
$ source .venv/bin/activate      # macOS / Linux
(.venv) $ python -m pip install --upgrade pip
(.venv) $ deactivate                 # leave the bubble
python -m
run a module as a script; python -m pip always uses the right pip
.venv
add it to .gitignore; rebuild it from requirements.txt
editor
VS Code + the Python extension; pick the .venv interpreter
Say it like a pro

"Works on my machine? Let's check which interpreter you're on: python -c "import sys; print(sys.executable)"."

REPL · ask one line at a time >>> 2 ** 101024 >>> "py" * 3'pypypy' script · runs top → bottom .py indentation is the syntax for n in range(3): if n % 2 == 0: print(n, "is even") 4 spaces per level · the colon opens a block
PLATE 2 — Try things in the REPL, keep things in a file.
Chapter 2 · Your first script

Hello, and why the spaces matter

Type python alone to open the REPL (Read-Eval-Print Loop), a scratchpad that answers each line. Real programs live in .py files that run top to bottom.

hello.py
# hello.py
name = input("What's your name? ")
print(f"Hello, {name}!")

for n in range(3):
    if n % 2 == 0:
        print(n, "is even")
Terminal
$ python hello.py
What's your name? Ada
Hello, Ada!
0 is even
2 is even
#
comment; Python ignores the rest of the line
help()
help(str) or dir(obj) in the REPL shows what something can do
PEP 8
the style guide: snake_case names, 4-space indents; let ruff or black enforce it
names are tags, not boxes age 30 int a b [1, 2, 3, 4] b = ab.append(4)a sees it too! the core types int42 float3.14 str"hi" boolTrue Nonenothing immutable: int float str bool tuple None mutable: list dict set (and most objects)
PLATE 3 — Two tags, one list. Mutate it through either name and both see the change.
Chapter 3 · Variables & types

Names point at objects

Python is dynamically typed: the object has a type, the name doesn't. = ties a name to an object. Add type hints so your editor and tools like mypy can catch mistakes.

types.py
age: int = 30
price: float = 19.99
name: str = "Ada"
active: bool = True
nothing: None = None

print(type(price), isinstance(age, int))
<class 'float'> True

a = [1, 2, 3]
b = a            # same object, second tag
b.append(4)
print(a, a is b)
[1, 2, 3, 4] True

c = a.copy()     # a real, separate copy
print(int("42") + 1, str(3.5), float("2"))
43 3.5 2.0
is vs ==
== same value · is same object (use is only for None)
// % **
floor divide · remainder · power: 7 // 2 = 3, 7 % 2 = 1
s = "PYTHON" 012345 PYTHON -6-5-4-3-2-1 s[0:2] → "PY" s[-3:] → "HON" slice = [start : stop : step] start included · stop excluded s[::2] → "PTO" s[::-1] → "NOHTYP" s[0] = "J" → TypeError (strings are immutable)
PLATE 4 — Count from the front with 0, from the back with -1.
Chapter 4 · Strings & f-strings

Text you can slice, format, and chain

A string is an immutable sequence of characters. Every method returns a new string, so you can chain them. f-strings are the modern way to put values into text.

strings.py
raw = "  ada lovelace  "
name = raw.strip().title()
print(f"Hi {name}! ({len(name)} chars)")
Hi Ada Lovelace! (12 chars)

print(name.split())            # → list of words
['Ada', 'Lovelace']
print("-".join(["2026", "10", "29"]))
2026-10-29

pi, users = 3.14159, 1234567
print(f"{pi:.2f} | {users:,} | {0.42:.0%} | {name!r}")
3.14 | 1,234,567 | 42% | 'Ada Lovelace'
print(f"{pi=}")                # debug print, 3.8+
pi=3.14159

path = r"C:\new\folder"        # raw string: no escapes
poem = """multi
line"""
in
"ada" in name.lower() → substring check
methods
.upper() .lower() .replace() .startswith() .find() .isdigit()
list · a train you can change 3 1 4 9 .append(9)adds a car at the end nums[0] → 3 nums[-1] → 9 nums[1:3] → [1, 4] len(nums) → 4 tuple · sealed, can't change (10, 20) x = 10 y = 20 unpacking which one? list → a collection of the same kind of thing that grows tuple → a fixed record: (lat, lon), (name, age), dict keys
PLATE 5 — Lists change, tuples don't. Unpacking hands each value its own name.
Chapter 5 · Lists & tuples

Ordered collections

A list [ ] is ordered and mutable: add, remove, sort in place. A tuple ( ) is ordered and immutable, so it's safe to share and can be a dict key.

lists.py
nums = [3, 1, 4]
nums.append(9)
nums.insert(0, 7)
nums.remove(1)                 # by value
last = nums.pop()              # removes + returns 9
print(nums, last)
[7, 3, 4] 9

print(sorted(nums), sorted(nums, reverse=True))
[3, 4, 7] [7, 4, 3]
words = ["kiwi", "fig", "banana"]
print(sorted(words, key=len))
['fig', 'kiwi', 'banana']

point = (10, 20)
x, y = point
first, *rest = [1, 2, 3, 4]
x, y = y, x                    # swap, no temp
print(first, rest, x, y)
1 [2, 3, 4] 20 10
sort vs sorted
.sort() changes the list, returns None · sorted() returns a new list
speed
append/pop at the end is O(1); x in list is O(n), so use a set for lookups
dict · labeled lockers "name""Ada" "role""admin" "age"36 "role" hash() jumps straight there:O(1), no searching set · unique items, fast "in" a, bcd, e AB A | B unionA & B → {c}A - B → {a, b}set(list) dedupes
PLATE 6 — Know the key, open the locker. No looking through every one.
Chapter 6 · Dictionaries & sets

Look things up by name, instantly

A dict maps keys to values using a hash table, so lookups are O(1). Keys must be immutable (str, int, tuple). Since 3.7 dicts keep insertion order. A set is a dict with only keys.

dicts.py
user = {"name": "Ada", "role": "admin"}
user["age"] = 36
print(user.get("email", "n/a"))   # no KeyError
n/a

for key, value in user.items():
    print(f"{key:>5} → {value}")
 name → Ada
 role → admin
  age → 36

defaults = {"theme": "dark", "role": "user"}
merged = defaults | user          # 3.9+, right side wins

from collections import Counter, defaultdict
print(Counter("mississippi").most_common(2))
[('i', 4), ('s', 4)]
groups = defaultdict(list)
groups["py"].append("ada")        # no setup needed

print({1, 1, 2, 3, 3} & {2, 3, 4})
{2, 3}
JSON
a dict looks just like JSON; json.loads() / json.dumps() convert
temp = 28 > 30? yes "Hot" no > 20? yes "Nice" no "Cold" falsy values FalseNone0 0.0"" (empty str)[] {} set() everything elseis truthy first True branch wins; the rest are skipped
PLATE 7 — Top to bottom, the first condition that's true wins.
Chapter 7 · Decisions

if, elif, else, and match

Conditions end in a colon and open an indented block. Combine with and, or, not. Python lets you chain comparisons like math: 20 < temp <= 30.

decide.py
temp = 28
if temp > 30:
    print("Hot")
elif 20 < temp <= 30:
    print("Nice")
else:
    print("Cold")
Nice

status = "ok" if temp < 40 else "danger"   # one-liner

items = []
if not items:                  # empty list is falsy
    print("nothing to do")

name = user_input or "guest"   # fallback value
match · structural pattern matching (3.10+)
match command.split():
    case ["go", direction]:
        print("moving", direction)
    case ["quit" | "exit"]:
        print("bye")
    case _:
        print("unknown")
Say it like a pro

"Write if items:, not if len(items) > 0:, and use if x is None, never == None."

for · one item at a time off the belt apple kiwi mango loop bodyprint(f) enumerate · stamp a number 1apple 2kiwi 3mango zip · walk two lists together names ["ada", "linus"]scores [ 95, 88 ] → ("ada", 95), ("linus", 88) while · repeat until False n > 0? break → leave the loop nowcontinue → skip to next itemforgot n -= 1? infinite loop (Ctrl+C)
PLATE 8 — for when you have the items, while when you have a condition.
Chapter 8 · Loops

Repeat without repeating yourself

A for loop walks any iterable: lists, strings, dicts, files, ranges. A while loop keeps going as long as its condition is true.

loops.py
fruits = ["apple", "kiwi", "mango"]
for i, fruit in enumerate(fruits, start=1):
    print(i, fruit)
1 apple
2 kiwi
3 mango

for name, score in zip(["ada", "linus"], [95, 88]):
    print(f"{name}: {score}")

for n in range(10, 0, -3):     # start, stop, step
    print(n, end=" ")
10 7 4 1

n = 3
while n > 0:
    print(n); n -= 1

for f in fruits:
    if f == "kiwi":
        break
else:                          # runs only if no break
    print("no kiwi found")
range
range(5) → 0..4; the stop number is never included
itertools
chain, product, groupby, islice for fancier loops
Say it like a pro

"If you're writing range(len(x)), you wanted enumerate(x)."

[n * n for n in nums if n % 2] 3 · make1 · take2 · keep? 1 2 3 4 filterif n % 2 2, 4 dropped transformn * n [1, 9] [ ] list · { } set · {k: v} dict · ( ) lazy generator
PLATE 9 — Take each item, keep the ones that pass, transform them, collect the result.
Chapter 9 · Comprehensions & generators

Build a collection in one readable line

A comprehension is a loop that builds a list, set or dict. Read it as: what to make, for each item, if it passes. Wrap it in parentheses and you get a generator that makes items one at a time and uses almost no memory.

comps.py
nums = [1, 2, 3, 4]
odd_squares = [n * n for n in nums if n % 2]
print(odd_squares)
[1, 9]

lengths = {w: len(w) for w in ["hi", "hello"]}
initials = {name[0] for name in ["ada", "alan", "bob"]}
print(lengths, initials)
{'hi': 2, 'hello': 5} {'a', 'b'}

total = sum(n * n for n in range(1_000_000))   # no giant list

def read_big(path):
    with open(path) as f:
        for line in f:
            yield line.strip()     # a generator function

flat = [x for row in [[1, 2], [3]] for x in row]
[1, 2, 3]
any / all
any(n > 3 for n in nums) stops at the first match
rule
if it doesn't fit on one line comfortably, use a regular loop
a function is a machine "Ada" excited= greet()name, excited→ str "Hello, Ada!" parameters in · return value out · no return → None where does Python find a name? LEGB B · Built-in (print, len) G · Global (module level) E · Enclosing function L · Localchecked first search inside→ out. assigning insidea function makesa new local
PLATE 10 — Inputs in, one value out. Names are looked up from the inside out.
Chapter 10 · Functions

Name a piece of work, then reuse it

def creates a function. Give parameters type hints and defaults, return a value, and write a docstring so help() can explain it. Functions are objects: pass them around like any value.

funcs.py
def greet(name: str, excited: bool = False) -> str:
    """Return a greeting for name."""
    end = "!" if excited else "."
    return f"Hello, {name}{end}"

print(greet("Ada"), greet("Linus", excited=True))
Hello, Ada. Hello, Linus!

def total(*nums: float, **opts) -> float:
    s = sum(nums)
    return round(s, opts.get("digits", 2))

print(total(1.234, 2.5, digits=1))
3.7

people = [("ada", 36), ("bob", 25)]
people.sort(key=lambda p: p[1])     # tiny inline function

def add_item(item, bag=None):       # NOT bag=[]
    bag = [] if bag is None else bag
    bag.append(item)
    return bag
*args
extra positional arguments, collected as a tuple
**kwargs
extra keyword arguments, collected as a dict
decorator
@cache, @property: a function that wraps another function
Say it like a pro

"A mutable default is created once and shared by every call. Default to None."

try:n = int(raw) error! ok except ValueError:handle it else:only on success finally:always runs (cleanup) Traceback (most recent call last): File "app.py", line 3, in <module> n = int(raw) ValueError: invalid literal for int(): 'abc' ↑ read up
PLATE 11 — Error goes left, success goes right, everyone meets at finally.
Chapter 11 · Errors & exceptions

Fail loudly, recover on purpose

When something goes wrong Python raises an exception. Read the traceback from the bottom: the last line names the error, the lines above show where. Catch only the errors you expect and can handle.

errors.py
raw = "abc"
try:
    n = int(raw)
except ValueError as e:
    print("Bad number:", e)
else:
    print("Got", n)
finally:
    print("done")
Bad number: invalid literal for int() with base 10: 'abc'
done

class InsufficientFunds(Exception):
    """Raised when a withdrawal is too large."""

def withdraw(balance: float, amount: float) -> float:
    if amount > balance:
        raise InsufficientFunds(f"need {amount - balance:.2f} more")
    return balance - amount

try:
    withdraw(50, 80)
except InsufficientFunds as e:
    print(e)
need 30.00 more
ExceptionUsually means
NameErrortypo, or used before assigned
TypeErrorwrong type: "3" + 4
KeyError / IndexErrormissing dict key / list position
AttributeErroroften a None you didn't expect
ModuleNotFoundErrornot installed in this venv
pathlib · paths are objects project/ ├─ data/ │ └─ notes.txt ├─ app.py └─ out/ Path("project") / "data" / "notes.txt" .name → "notes.txt".stem → "notes".suffix → ".txt".parent → project/data.exists() · .glob("*.txt")works on Windows + Mac with · the door that closes itself 1 open the file 2 read / write inside 3 leave the block → closed automatically, even after an error
PLATE 12 — Build paths with /, open files with with.
Chapter 12 · Files, pathlib & context managers

Read and write files safely

pathlib.Path treats paths as objects that work on every OS. A with block is a context manager: it guarantees cleanup (closing the file) no matter how the block exits.

files.py
from pathlib import Path
import csv, json

data = Path("data")
data.mkdir(exist_ok=True)
notes = data / "notes.txt"

notes.write_text("line 1\nline 2\n", encoding="utf-8")
print(notes.read_text(encoding="utf-8").splitlines())
['line 1', 'line 2']

with notes.open("a", encoding="utf-8") as f:   # a = append
    f.write("line 3\n")

with notes.open(encoding="utf-8") as f:
    for line in f:                 # streams, big files OK
        print(line.rstrip())

(data / "cfg.json").write_text(json.dumps({"debug": True}, indent=2))
cfg = json.loads((data / "cfg.json").read_text())

with open(data / "people.csv", newline="") as f:
    for row in csv.DictReader(f):
        print(row["name"])

for p in Path(".").rglob("*.py"):
    print(p)
modes
"r" read · "w" overwrite · "a" append · "rb" binary
encoding
always pass encoding="utf-8"; Windows defaults differ
class Account fieldsowner: strbalance: float methodsdeposit(amt) the blueprint a = Account("Ada")balance 50.0 b = Account("Bob")balance 0.0 c = Account("Cy")balance 900.0 instances: same shape, own data inheritance · "is a" Account SavingsAccount gets deposit() for free,adds add_interest() self = "this particular instance"
PLATE 13 — One blueprint, many objects, each holding its own data.
Chapter 13 · Classes & dataclasses

Bundle data with the code that uses it

A class defines a new type; each instance holds its own data. Methods take self, the instance they were called on. For classes that mostly hold data, @dataclass writes __init__, __repr__ and __eq__ for you.

accounts.py
from dataclasses import dataclass, field

@dataclass
class Account:
    owner: str
    balance: float = 0.0
    history: list[float] = field(default_factory=list)

    def deposit(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("amount must be positive")
        self.balance += amount
        self.history.append(amount)

    @property
    def is_rich(self) -> bool:
        return self.balance > 1_000

@dataclass
class SavingsAccount(Account):
    rate: float = 0.04

    def add_interest(self) -> None:
        self.deposit(self.balance * self.rate)

a = SavingsAccount("Ada", 1000)
a.add_interest()
print(a.balance, a.is_rich)
1040.0 True
print(Account("Bob"))
Account(owner='Bob', balance=0.0, history=[])
dunder
"double underscore" methods like __len__ and __str__ plug into built-ins
frozen
@dataclass(frozen=True) makes instances immutable
main.py utils.py from utils import slugify PyPI500k+ packages pip install requests .venv/site-packagesrequests · urllib3 · … import requests if __name__ == "__main__": main() python main.py → __name__ is "__main__" → runs import main → __name__ is "main" → skipped
PLATE 14 — Your files, the standard library, and PyPI all come in through import.
Chapter 14 · Modules, packages & pip

Split code up and stand on others' shoulders

Every .py file is a module; a folder of them is a package. Python ships a huge standard library (json, csv, datetime, pathlib, re, sqlite3), and pip installs the rest from PyPI into your venv.

Terminal · inside the venv
(.venv) $ pip install requests rich
(.venv) $ pip freeze > requirements.txt
(.venv) $ pip install -r requirements.txt   # on another machine
(.venv) $ pip list --outdated
utils.py + main.py
# utils.py
import re

def slugify(text: str) -> str:
    return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")

# main.py
import requests
from utils import slugify

def main() -> None:
    r = requests.get("https://api.github.com", timeout=10)
    r.raise_for_status()
    print(r.status_code, slugify("Hello, World!"))

if __name__ == "__main__":
    main()
200 hello-world
uv
a much faster drop-in for pip + venv: uv venv, uv pip install
pyproject
pyproject.toml is the modern place for deps and tool config
expenses.csv readpathlib + with parse@dataclass rows filtercomprehension totaldefaultdict try /except 1 2 3 4 5 $ python spend.py --min 5 food $ 86.40 transport $ 42.00 fun $ 25.00 1 read file · 2 turn rows into objects · 3 keep rows ≥ min 4 sum by category · 5 print sorted report bad rows are skipped and counted, not crashed on
PLATE 15 — One small program that uses every chapter in this book.
Chapter 15 · How it all comes together

Build a real tool: an expense report

  1. Set up: folder, python -m venv .venv, activate (1).
  2. Model a row as a dataclass with type hints (3, 13).
  3. Read the CSV with pathlib and with (12).
  4. Guard bad rows with a specific except (11).
  5. Filter + total with a comprehension and a dict (6, 9).
  6. Print with f-string alignment, and run it from __main__ (4, 14).
spend.py
import argparse, csv
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path

@dataclass
class Expense:
    category: str
    amount: float

def load(path: Path) -> tuple[list[Expense], int]:
    rows, bad = [], 0
    with path.open(newline="", encoding="utf-8") as f:
        for r in csv.DictReader(f):
            try:
                rows.append(Expense(r["category"], float(r["amount"])))
            except (KeyError, ValueError):
                bad += 1
    return rows, bad

def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--file", type=Path, default=Path("expenses.csv"))
    ap.add_argument("--min", type=float, default=0)
    args = ap.parse_args()

    rows, bad = load(args.file)
    totals: dict[str, float] = defaultdict(float)
    for e in [e for e in rows if e.amount >= args.min]:
        totals[e.category] += e.amount

    for cat, amt in sorted(totals.items(), key=lambda kv: -kv[1]):
        print(f"{cat:<10}${amt:>8.2f}")
    if bad:
        print(f"({bad} bad rows skipped)")

if __name__ == "__main__":
    main()
The cheat sentence

"Names point at objects, lists and dicts hold them, loops and comprehensions walk them, functions and classes organize them, with and try keep them safe, and the venv keeps it all reproducible."