Most common Python statement.
print("Hello, World!")Patterns from the Foundations track, condensed into one page. Skim, copy, adapt. Pair with the linked lessons when you want the full "why".
Most common Python statement.
print("Hello, World!")Inline expression in a string. The default since 3.6.
name = "Ada"
age = 36
print(f"{name} is {age}")Find out what something is.
isinstance(x, (int, float))
Convert between types — always explicit.
n = int("42")
s = str(3.14)Triple-quoted; preserves line breaks.
doc = """ Line 1 Line 2 """
Tokenise text and put it back.
"a,b,c".split(",") # → ["a","b","c"]
",".join(["a","b","c"])Branch on a condition. No switch in Python.
if x > 0:
...
elif x == 0:
...
else:
...Empty, 0, None, "" are falsy. Everything else is truthy.
if data:
process(data)One-line if/else for assignment.
sign = "+" if x >= 0 else "-"
Ordered, mutable, indexable.
xs = [1, 2, 3] xs.append(4)
Like list, but immutable. Good for fixed records.
point = (3, 4)
Unique values, O(1) membership.
unique = set(xs) 3 in unique
Hash map from keys to values. Order-preserving since 3.7.
user = {"name": "Ada", "age": 36}Substring/sublist with `[start:stop:step]`.
first3 = xs[:3] reverse = xs[::-1]
Filtered / mapped list in one line.
evens = [x for x in xs if x % 2 == 0]
Build a dict in one expression.
squared = {x: x*x for x in range(5)}Default loop.
for x in xs:
process(x)Loop with an index counter.
for i, x in enumerate(xs, start=1):
print(i, x)Walk two iterables in parallel.
for name, age in zip(names, ages):
...Loop until a condition flips. Less common.
while not done:
step()Exit / skip an iteration.
for x in xs:
if x < 0:
continue
if x > 100:
breakDefine a function.
def greet(name: str) -> str:
return f"Hello, {name}"Fallback values for parameters.
def repeat(x, n=2):
return x * nCapture variable positional + keyword args.
def f(*args, **kwargs):
...Anonymous one-liner. Use for short callbacks.
add = lambda a, b: a + b
Handle exceptions; be specific.
try:
n = int(s)
except ValueError:
n = 0Throw a specific exception.
raise ValueError("must be positive")Read/write a file with auto-cleanup.
with open("data.txt") as f:
text = f.read()Want to actually learn these patterns, not just paste them? Open the Python basics cheatsheet track — each snippet has a full lesson behind it.