Quick reference

Python cheatsheet

Syntax and patterns you actually type—on one scrollable page.

Unlike the tutorial roadmap (order of chapters) or exercises (problems + solutions), this page is dense reference material: operators, collections, control flow, functions, classes, files, and errors. Use it while coding; use the course when something feels unexplained.

Operators & comparisons

TopicExamples
Arithmetic+ - * / // % **
Compare / chain== != < > <= >= · 1 < x < 10
Logicand or not
Identity / membershipis is not · in not in

Types & truthiness

type(x)          # class of value
bool([])         # False — empty container
bool(""), 0, None  # all falsy

Strings

s = "hello"
s.lower(); s.strip(); s.split(",")
",".join(parts)
s.startswith("h"); s.find("l")   # index or -1
f"{n=} {x=}"                     # debug f-string (3.8+)

list · tuple · dict · set

xs = [1, 2, 3]
xs.append(4); xs.pop(); xs[::-1]
{k: xs[k] for k in range(len(xs))}   # dict comp idea

d = {"a": 1}
d.get("b", 0); d.keys(); d.items()

a = {1, 2}; b = {2, 3}
a | b   # union (3.9+), or a.union(b)

Control flow

if cond:
    ...
elif other:
    ...
else:
    ...

for i, v in enumerate(items):
    ...

while cond:
    ...

match x:          # 3.10+ structural pattern match
    case int(n):
        ...

Functions & comprehensions

def f(a, b=1, *args, c, d=2, **kwargs): ...

[x*x for x in range(10) if x % 2 == 0]
{str(x): x for x in items}

lambda x: x + 1

Classes (minimal)

class Box:
    def __init__(self, w):
        self.w = w
    def area(self):
        return self.w * self.w

class Cube(Box):
    def volume(self):
        return self.w ** 3

Files

with open("f.txt", "r", encoding="utf-8") as f:
    data = f.read()          # whole file
    # or for line in f:

with open("out.txt", "w") as f:
    f.write("hi\n")

Errors

try:
    risky()
except ValueError as e:
    ...
except (TypeError, KeyError):
    ...
else:        # no exception
    ...
finally:     # always
    ...

Go deeper (not duplicate content)

FAQs

Is this a replacement for the Python course?

No. This cheatsheet is for quick lookup while coding or revising. The course explains why things work, edge cases, and larger examples.

How should I use this page?

Skim before a coding session, keep it open while you build a small project, and update your own notes in a doc when you discover patterns you personally forget.

Does it cover advanced topics?

It covers everyday syntax through basics of classes, comprehensions, and file I/O. For async, packaging, or advanced stdlib topics, follow the linked course chapters.

Canonical: https://www.schoolabe.com/python-cheatsheet