Skip to content

03. Control flow — Cheat sheet

The essentials of module 03 on one page. Every runnable block on this page is checked against its output.

I want to… Use… Example
run code only when a condition holds if if reading > 23.0:
choose one of several branches if / elif / else most severe test first
choose between two values in one line conditional expression "low" if logins <= 3 else "ok"
test “not empty” truthiness if readings:
test “missing” is None if value is None:
use a default only for a missing value conditional expression 0.0 if d is None else d
guard a risky operation short-circuit and n > 0 and total / n > 100
test membership in a few values in with a tuple if status in ("warn", "fail"):
dispatch on the shape of a record match / case case {"status": 429, "retry_after": s}:
match one of several literals or-pattern case "warn" | "fail":
match “anything else” wildcard case _:
add a condition to a pattern guard case {"status": c} if c >= 500:
repeat for each item for for reading in readings:
repeat n times range(n) for _ in range(3):
loop over numbers with a step range(start, stop, step) range(0, 60, 10)
get position and item enumerate() enumerate(lines, start=1)
loop over parallel lists zip(..., strict=True) zip(ids, temps, strict=True)
pair each item with the next one zip(xs[:-1], xs[1:]) consecutive differences
repeat until a condition changes while while attempt < max_attempts:
skip the rest of one iteration continue skip a broken line
leave the loop early break stop at the first failure
report “not found” after a search loop else for ... break ... else:
stop a hanging script Ctrl+C in the terminal
temperature_c = 23.4
if temperature_c > 23.0: # the header line ends with a colon
print("too warm") # 4 spaces: inside the block
print("check the air conditioning")
print("done") # back at the left margin: after the block
Output
too warm
check the air conditioning
done
Rule Detail
Header lines if, elif, else, for, while, match, case end with :
Indent 4 spaces per level (PEP 8); never mix tabs and spaces
Empty block pass does nothing, as a placeholder
Wrong indent IndentationError before the script runs
for temperature_c in [18.7, 21.4, 23.6]:
if temperature_c < 19.0:
band = "too cold"
elif temperature_c <= 23.0: # only reached when temperature_c >= 19.0
band = "normal"
else:
band = "too warm"
print(temperature_c, band)
Output
18.7 too cold
21.4 normal
23.6 too warm
Fact Detail
Only one branch runs the first true condition wins; the rest are skipped
Order most severe or most specific test first
elif any number, after if
else at most one, last; optional
Nested if an if inside a block; often clearer as and
logins, tickets = 2, 1
print("low" if logins <= 3 else "normal")
print(f"{tickets} ticket{'' if tickets == 1 else 's'}")
discount = None
print(0.0 if discount is None else discount) # default only for None
Output
low
1 ticket
0.0
Falsy Truthy
False, None True
0, 0.0 any other number
"" any non-empty string, also " ", "0", "False"
[], {}, (), range(0) any non-empty container, also [0], [None]
Intent Write Avoid
not empty if items: if len(items) > 0:
empty if not items: if items == []:
missing if x is None: if not x: (0 looks missing)
present if x is not None: if x: (0 looks absent)
a flag if has_autopay: if has_autopay == True:
readings = []
print(readings or "no data") # `or` returns the first truthy operand
print(bool([0]), bool({}), bool(" "))
order_count, total = 0, 0.0
print(order_count > 0 and total / order_count > 100) # no ZeroDivisionError
Output
no data
True False True
False
Expression Returns
a and b a if a is falsy, else b
a or b a if a is truthy, else b
not a always a bool
responses = [
{"status": 200, "data": []},
{"status": 200, "data": [{"id": "P001"}, {"id": "P002"}]},
{"status": 429, "retry_after": 30},
{"status": 503, "error": "service_unavailable"},
{"detail": "timeout"},
]
for response in responses:
match response:
case {"status": 200, "data": []}: # an empty list
print("empty page")
case {"status": 200, "data": [first, *rest]}: # 1 or more items
print(1 + len(rest), "items, first", first["id"])
case {"status": 429, "retry_after": int(seconds)}: # class pattern
print("wait", seconds, "s")
case {"status": int(code)} if code >= 500: # guard
print("server error", code)
case _:
print("unknown shape")
Output
empty page
2 items, first P001
wait 30 s
server error 503
unknown shape
Pattern Syntax Matches
literal 200, "ok", None, True an equal value (None, True, False by identity)
or "warn" | "fail" any alternative
wildcard _ anything, binds nothing
capture name anything, binds it to name
value Status.OK (a dotted name) equal to that constant (enums, module 21)
sequence [a, b], (a, b) a list or tuple of exactly 2 items (never a str)
sequence with rest [first, *rest] 1 or more items; rest is a list
empty sequence [] an empty list or tuple
mapping {"type": "order", "id": i} a dict with these keys; extra keys allowed
mapping with rest {"type": t, **others} binds the other keys to a dict
class int(x), float(x), str(s) a value of that type
as ("ok" | "warn") as status the sub-pattern; binds the matched value
guard case p if condition: the pattern and the condition
for message in ["READ S1 20.21", "BATCH S2 22.30 22.44", "STATUS S4 warn", "PING", ""]:
match message.split():
case ["READ", sensor_id, value]:
print("read", sensor_id, value)
case ["BATCH", sensor_id, *values] if values:
print("batch", sensor_id, len(values))
case ["STATUS", sensor_id, ("ok" | "warn" | "fail") as status]:
print("status", sensor_id, status)
case [command]:
print("bare command", command)
case []:
print("empty")
Output
read S1 20.21
batch S2 2
status S4 warn
bare command PING
empty
Rule Detail
First match wins order cases from specific to general
No match, no case _ nothing happens, no error
case NAME: captures everything; a SyntaxError if it is not the last case
Compare with a variable use a guard: case x if x == limit:
Strings are not sequences here split first: match line.split():
Python version 3.10 and newer
readings = [21.0, 21.9, 21.4, 22.5]
for reading in readings: # one iteration per item
print(reading, "°C")
for character in "S1": # a string is iterable too
print(character)
Output
21.0 °C
21.9 °C
21.4 °C
22.5 °C
S
1
Iterable The loop variable gets
list each item
string each character
dict each key (module 04: .items() for key and value)
range(...) each number
file lines each line (module 07)
Call Numbers Length
range(4) 0, 1, 2, 3 4
range(1, 5) 1, 2, 3, 4 4
range(0, 60, 10) 0, 10, …, 50 6
range(10, 0, -3) 10, 7, 4, 1 4
range(0) (none) 0
print(list(range(0, 43, 6))) # first line index of each hour of readings.txt
print(len(range(0, 60, 10)), 60 in range(0, 60, 10)) # the stop is excluded
for _ in range(2): # `_` when the number is not used
print("retry")
Output
[0, 6, 12, 18, 24, 30, 36, 42]
6 False
retry
retry
lines = ["21.0", "error", "21.4"]
for number, line in enumerate(lines, start=1):
print(number, line)
ids, temps = ["S1", "S2"], [20.21, 22.30]
for sensor_id, temp in zip(ids, temps, strict=True):
print(sensor_id, temp)
values = [21.0, 21.9, 21.4]
for before, after in zip(values[:-1], values[1:], strict=True):
print(f"{after - before:+.1f}") # consecutive changes
Output
1 21.0
2 error
3 21.4
S1 20.21
S2 22.3
+0.9
-0.5
Call Gives Note
enumerate(xs) (0, x0), (1, x1), …
enumerate(xs, start=1) (1, x0), (2, x1), … line numbers
zip(a, b) (a0, b0), (a1, b1), … stops at the shortest, silently
zip(a, b, strict=True) the same ValueError if the lengths differ
enumerate(zip(a, b)) (i, (a_i, b_i)) unpack with for i, (x, y) in ...
users, months = 1200.0, 0
while users < 5000: # checked before every iteration
users *= 1.08
months += 1
print(months, round(users))
attempt, max_attempts = 0, 3
while True: # loop forever ...
attempt += 1
if attempt >= max_attempts: # ... until a break
break
print("stopped at attempt", attempt)
Output
19 5179
stopped at attempt 3
Use while when Example
the number of iterations is unknown retry until success, train until convergence
you wait for a value to cross a limit grow until a target
you read until a sentinel stop at a STOP line

A sentinel is a special value that marks the end of the data. Always make sure the condition can become false, and add a limit such as max_iter.

for line in ["21.0", "", "n/a", "38.5", "21.4"]:
if not line or line == "n/a":
continue # skip this item
if float(line) > 30.0:
print("fault:", line)
break # leave the loop; the else block is skipped
print("ok:", line)
else:
print("no fault") # runs only if the loop did not break
Output
ok: 21.0
fault: 38.5
Statement Effect In nested loops
continue jump to the next iteration innermost loop only
break leave the loop at once innermost loop only
else: after for or while runs when the loop ended without break belongs to its own loop
pass do nothing —
readings = [21.0, 21.9, 21.4, 22.5, 22.9]
total, count, warm, highest, first_warm = 0.0, 0, [], readings[0], None
for reading in readings:
total += reading # sum
count += 1 # count
if reading > 22.0:
warm.append(reading) # filter
if first_warm is None:
first_warm = reading # first match (search)
if reading > highest:
highest = reading # maximum
print(round(total / count, 2), warm, highest, first_warm)
Output
21.94 [22.5, 22.9] 22.9 22.5
Pattern Loop Built-in or later idiom
sum total += x sum(xs)
count if test: n += 1 sum(1 for x in xs if test)
filter if test: kept.append(x) [x for x in xs if test] (module 04)
transform out.append(f(x)) [f(x) for x in xs] (module 04)
min / max if x > best: best = x max(xs), max(xs, key=...) (module 05)
any / all flag and break any(...), all(...)
search break + loop else next((x for x in xs if test), None) (module 10)
count by key counts[k] += 1 collections.Counter (module 09)
pairs of neighbors zip(xs[:-1], xs[1:]) itertools.pairwise(xs) (module 09)
  • Only the first true branch of an if-elif chain runs. A mild test before a severe one hides the severe one.
  • if x == 1 or 2: is always true. Write x == 1 or x == 2, or x in (1, 2).
  • if not value: treats a real 0, 0.0 or "" as missing. Use is None.
  • value or default replaces a real 0. Use default if value is None else value.
  • None >= 42 raises a TypeError. Check for None before you compare.
  • sum(xs) / len(xs) on an empty list raises a ZeroDivisionError. Guard with if xs:.
  • range(a, b) excludes b. range(0, 60, 10) ends at 50.
  • zip() drops extra items silently. Use strict=True when lengths must match.
  • Do not add or remove items of a list while you loop over it. Build a new list.
  • A while loop needs something that changes its condition. Add max_iter.
  • A loop else runs when there was no break, also for an empty iterable. Align it with for, not with if.
  • break and continue affect only the innermost loop.
  • A bare name in a case captures; it never compares. case limit: matches everything.
  • A sequence pattern never matches a str. Split the text first.
  • A mapping pattern ignores extra keys, and an empty mapping pattern {} matches every dict.
  • The first matching case wins. Put specific cases ("data": []) before general ones ("data": items).
  • The loop variable keeps its last value after the loop. Do not rely on it if the loop could run zero times.