Fifteen spreads. Each one has a picture, the idea behind it, and real code you can paste into a terminal or a .py file.
"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.
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.
$ 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 pip always uses the right pip.gitignore; rebuild it from requirements.txt.venv interpreter"Works on my machine? Let's check which interpreter you're on: python -c "import sys; print(sys.executable)"."
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
name = input("What's your name? ")
print(f"Hello, {name}!")
for n in range(3):
if n % 2 == 0:
print(n, "is even")$ python hello.py What's your name? Ada Hello, Ada! 0 is even 2 is even
help(str) or dir(obj) in the REPL shows what something can dosnake_case names, 4-space indents; let ruff or black enforce itPython 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.
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
== same value · is same object (use is only for None)7 // 2 = 3, 7 % 2 = 1A 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.
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""""ada" in name.lower() → substring check.upper() .lower() .replace() .startswith() .find() .isdigit()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.
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() changes the list, returns None · sorted() returns a new listx in list is O(n), so use a set for lookupsA 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.
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.loads() / json.dumps() convertConditions end in a colon and open an indented block. Combine with and, or, not. Python lets you chain comparisons like math: 20 < temp <= 30.
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 valuematch command.split():
case ["go", direction]:
print("moving", direction)
case ["quit" | "exit"]:
print("bye")
case _:
print("unknown")"Write if items:, not if len(items) > 0:, and use if x is None, never == None."
for when you have the items, while when you have a condition.A for loop walks any iterable: lists, strings, dicts, files, ranges. A while loop keeps going as long as its condition is true.
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(5) → 0..4; the stop number is never includedchain, product, groupby, islice for fancier loops"If you're writing range(len(x)), you wanted enumerate(x)."
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.
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(n > 3 for n in nums) stops at the first matchdef 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.
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@cache, @property: a function that wraps another function"A mutable default is created once and shared by every call. Default to None."
finally.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.
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| Exception | Usually means |
|---|---|
| NameError | typo, or used before assigned |
| TypeError | wrong type: "3" + 4 |
| KeyError / IndexError | missing dict key / list position |
| AttributeError | often a None you didn't expect |
| ModuleNotFoundError | not installed in this venv |
/, open files with with.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.
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)"r" read · "w" overwrite · "a" append · "rb" binaryencoding="utf-8"; Windows defaults differA 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.
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=[])__len__ and __str__ plug into built-ins@dataclass(frozen=True) makes instances immutableimport.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.
(.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 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 venv, uv pip installpyproject.toml is the modern place for deps and tool configpython -m venv .venv, activate (1).with (12).except (11).__main__ (4, 14).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()"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."