← Back to Python track
Reference

Python Cheat Sheet

Every core Python pattern from the track on one page — syntax, data structures, functions, classes, files and the standard library. Bookmark it.

Basics
Variables & types
x = 42          # int
pi = 3.14       # float
name = "Ava"    # str
ok = True       # bool
nothing = None  # NoneType
Convert types
int("7")      # 7
float("3.5")  # 3.5
str(42)       # "42"
bool("")      # False
f-string formatting
f"{name} is {x}"
f"{pi:.2f}"        # 3.14
f"{1234567:,}"     # 1,234,567
f"{0.25:.0%}"      # 25%
Comparison & logic
a == b   a != b   a < b
and   or   not
x in items       # membership
a is None        # identity
Strings
Index & slice
s[0]      # first char
s[-1]     # last char
s[1:4]    # chars 1,2,3
s[::-1]   # reversed
Common methods
s.upper()  s.lower()  s.strip()
s.replace("a", "b")
s.split(",")   ",".join(parts)
s.startswith("http")  s.find("x")
Lists
Create & access
nums = [3, 1, 2]
nums[0]        # 3
nums[-1]       # 2
nums[1:3]      # [1, 2]
Modify
nums.append(4)
nums.extend([5, 6])
nums.insert(0, 9)
nums.remove(1)   nums.pop()
Sort
nums.sort()              # in place
sorted(nums, reverse=True)
sorted(rows, key=lambda r: r[1])
Comprehension
[n * n for n in nums]
[n for n in nums if n > 1]
["even" if n % 2 == 0 else "odd" for n in nums]
Dicts, sets & tuples
Dict
d = {"a": 1, "b": 2}
d["a"]            # 1
d.get("x", 0)     # default
for k, v in d.items(): ...
Set
s = {1, 2, 3}
s.add(4)
a & b   a | b   a - b   # ∩ ∪ difference
x in s            # O(1)
Tuple & unpack
point = (3, 4)
x, y = point
first, *rest = [1, 2, 3, 4]
Control flow
if / elif / else
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"
for / while
for i in range(5): ...
for x in items: ...
for i, x in enumerate(items): ...
while cond: ...
break / continue
for x in items:
    if x < 0:
        continue   # skip
    if x > 100:
        break      # stop
Functions
Define & return
def add(a, b=0):
    return a + b

add(2)      # 2
add(2, 3)   # 5
*args / **kwargs
def f(*args, **kwargs):
    print(args)    # tuple
    print(kwargs)  # dict
f(1, 2, x=3)
Lambda
square = lambda n: n * n
sorted(data, key=lambda r: r["age"])
Avoid mutable default
def f(items=None):
    items = [] if items is None else items
    ...
Classes
Define a class
class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance
    def deposit(self, amount):
        self.balance += amount
Inheritance
class Savings(Account):
    def __init__(self, owner, rate):
        super().__init__(owner)
        self.rate = rate
Dunder methods
def __repr__(self): return f"Account({self.owner})"
def __eq__(self, other): return self.id == other.id
def __len__(self): return len(self.items)
Errors & files
try / except
try:
    n = int(text)
except ValueError:
    n = 0
else:
    print("ok")
finally:
    cleanup()
Read & write files
with open("data.txt") as f:
    for line in f:
        print(line.rstrip())

with open("out.txt", "w") as f:
    f.write("hello\n")
Raise
if x < 0:
    raise ValueError("x must be >= 0")
Comprehensions & iterators
Dict / set comp
{n: n * n for n in range(3)}
{len(w) for w in words}
Generator
def squares(n):
    for i in range(n):
        yield i * i

gen = (x * x for x in range(1000))
map / filter
list(map(str, nums))
list(filter(lambda n: n > 0, nums))
Standard library
collections
from collections import Counter, defaultdict
Counter(words).most_common(3)
defaultdict(list)
json & csv
import json, csv
json.loads(text)   json.dumps(obj)
for row in csv.DictReader(f): ...
datetime
from datetime import datetime, timedelta
datetime.now()
dt + timedelta(days=3)
dt.strftime("%Y-%m-%d")
pathlib
from pathlib import Path
Path("data") / "in.csv"
p.exists()   p.read_text()

Projects to build

The fastest way to make this stick. Build one, then put it in your portfolio.

Beginner

CSV cleaner CLI

A command-line tool that reads a messy CSV, drops bad rows, normalises types, and writes a clean file. Report how many rows were dropped and why.

argparsecsverror handlingfile I/O
Beginner

Expense tracker

Store expenses in a JSON file; add, list, and total them by category from the command line. Persist between runs.

jsondictsfunctionsCLI
Intermediate

Weather fetcher

Call a public weather API for several cities, handle timeouts and rate limits with retries, and print a formatted summary.

requestsretriesf-stringsenv vars
Intermediate

Log analyser

Parse a web server log with a regex, count status codes and top URLs, and flag error spikes. Stream the file line by line for constant memory.

regexgeneratorsCounterperformance
Advanced

Mini task queue

A small library where tasks are functions registered with a decorator, run with retries and logging, and results tracked. Add unit tests.

decoratorsOOPloggingpytest