Cheat sheets
Python cheat sheet
Quick reference for essential Python syntax: types, collections, control flow, and functions.
Types and variables
x = 5; s = "text"; b = True- Assignment and type inference.
type(x)- Returns a value's type.
int("5"), str(5), float("3.1")- Explicit conversion between types.
f"Hello {name}"- f-string: interpolates variables into text.
Collections
items = [1, 2, 3]- List: ordered and mutable.
tup = (1, 2, 3)- Tuple: ordered and immutable.
d = {"a": 1}- Dictionary: key-value pairs.
s = {1, 2, 3}- Set: unique values, unordered.
[x * 2 for x in items]- List comprehension.
Control flow
if x > 0: ... elif x == 0: ... else: ...- if/elif/else conditional.
for item in items: ...- Iterates over a collection.
while condition: ...- Repeats while the condition is true.
try: ... except ValueError: ...- Catches a specific exception.
Functions
def add(a, b=0): return a + b- Function with a default argument.
def total(*args, **kwargs): ...- Variable positional and keyword arguments.
lambda x: x * 2- Single-expression anonymous function.