03. Control flow — Cheat sheet
The essentials of module 03 on one page. Every runnable block on this page is checked against its output.
Quick lookup
Section titled “Quick lookup”| 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 |
Blocks and indentation
Section titled “Blocks and indentation”temperature_c = 23.4if 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 blocktoo warmcheck the air conditioningdone| 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 |
if, elif, else
Section titled “if, elif, else”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)18.7 too cold21.4 normal23.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 |
Conditional expressions
Section titled “Conditional expressions”logins, tickets = 2, 1print("low" if logins <= 3 else "normal")print(f"{tickets} ticket{'' if tickets == 1 else 's'}")discount = Noneprint(0.0 if discount is None else discount) # default only for Nonelow1 ticket0.0Truthiness
Section titled “Truthiness”| 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 operandprint(bool([0]), bool({}), bool(" "))order_count, total = 0, 0.0print(order_count > 0 and total / order_count > 100) # no ZeroDivisionErrorno dataTrue False TrueFalse| 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 |
match-case
Section titled “match-case”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")empty page2 items, first P001wait 30 sserver error 503unknown 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")read S1 20.21batch S2 2status S4 warnbare command PINGempty| 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 |
for loops
Section titled “for loops”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)21.0 °C21.9 °C21.4 °C22.5 °CS1| 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) |
range()
Section titled “range()”| 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.txtprint(len(range(0, 60, 10)), 60 in range(0, 60, 10)) # the stop is excludedfor _ in range(2): # `_` when the number is not used print("retry")[0, 6, 12, 18, 24, 30, 36, 42]6 Falseretryretryenumerate() and zip()
Section titled “enumerate() and zip()”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 changes1 21.02 error3 21.4S1 20.21S2 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 ... |
while loops
Section titled “while loops”users, months = 1200.0, 0while users < 5000: # checked before every iteration users *= 1.08 months += 1print(months, round(users))
attempt, max_attempts = 0, 3while True: # loop forever ... attempt += 1 if attempt >= max_attempts: # ... until a break breakprint("stopped at attempt", attempt)19 5179stopped at attempt 3Use 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.
break, continue and loop else
Section titled “break, continue and loop else”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 breakok: 21.0fault: 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 | — |
Loop patterns
Section titled “Loop patterns”readings = [21.0, 21.9, 21.4, 22.5, 22.9]total, count, warm, highest, first_warm = 0.0, 0, [], readings[0], Nonefor 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 # maximumprint(round(total / count, 2), warm, highest, first_warm)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) |
Gotchas
Section titled “Gotchas”- Only the first true branch of an
if-elifchain runs. A mild test before a severe one hides the severe one. if x == 1 or 2:is always true. Writex == 1 or x == 2, orx in (1, 2).if not value:treats a real0,0.0or""as missing. Useis None.value or defaultreplaces a real0. Usedefault if value is None else value.None >= 42raises aTypeError. Check forNonebefore you compare.sum(xs) / len(xs)on an empty list raises aZeroDivisionError. Guard withif xs:.range(a, b)excludesb.range(0, 60, 10)ends at 50.zip()drops extra items silently. Usestrict=Truewhen lengths must match.- Do not add or remove items of a list while you loop over it. Build a new list.
- A
whileloop needs something that changes its condition. Addmax_iter. - A loop
elseruns when there was nobreak, also for an empty iterable. Align it withfor, not withif. breakandcontinueaffect only the innermost loop.- A bare name in a
casecaptures; 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
casewins. 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.