Skip to content

03. Control flow

Until now, every script ran each line once, from top to bottom. Real data work needs more. A cleaning step must decide what to do with each row. A report must repeat the same calculation for every sensor. A training loop must run until the model stops improving. This module gives you the tools to decide and to repeat. The examples use sensor readings, order lines, customer records and API responses.

  • Choose between actions with if, elif and else, and order the conditions correctly.
  • Use truthiness to test for empty text, empty containers and None, and know when an explicit test is safer.
  • Match structured records, such as API responses and event messages, with match-case patterns and guards.
  • Repeat work with for and while loops, and use range(), enumerate() and zip().
  • Control a loop with break and continue, and use a loop else for a search that can find nothing.
  • Apply the standard loop patterns: count, total, filter, track the maximum and search.

Control flow is the order in which Python runs the statements of a program. By default, Python runs them from top to bottom, once each. Two kinds of statements change this order:

  • A branch runs a piece of code only when a condition is true. Python’s branch statements are if and match.
  • A loop runs a piece of code again and again. Python’s loop statements are for and while.

A condition is an expression that Python treats as true or false, such as reading > 23.0. Every data pipeline is built from these two tools. It loops over the rows, and for each row it decides: keep, fix, skip or stop.

flowchart LR
    A["Next row"] --> B{"Valid?"}
    B -- "yes" --> C["Use it"]
    B -- "no" --> D["Skip it"]
    C --> E{"More rows?"}
    D --> E
    E -- "yes" --> A
    E -- "no" --> F["Report"]

A branch or a loop controls a group of statements. This group is a block. Python marks a block with indentation: spaces at the start of each line. The line that opens the block ends with a colon (:). Every line of the block is indented by the same amount. The first line that is not indented ends the block.

reading = 23.4
if reading > 23.0:
print("Too warm:", reading)
print("Check the air conditioning.")
print("Check finished.")
Output
Too warm: 23.4
Check the air conditioning.
Check finished.

The two indented lines belong to the if block, so they run only when the condition is true. The last line is not indented. It runs in every case. PEP 8 asks for 4 spaces per level. Your editor inserts them when you press Tab in a .py file.

Indentation is part of Python’s grammar, not decoration. A wrong indent is an error:

reading = 23.4
if reading > 23.0:
print("Too warm:", reading)
Output
IndentationError: expected an indented block after 'if' statement on line 2

Python reads the whole file before it runs it, so this error stops the script before the first line runs. Never mix tabs and spaces in one file.

A block cannot be empty. When you need a block that does nothing yet, for example while you sketch a script, write pass. It is a statement that does nothing and only fills the place. The starter code of the exercises uses it.

reading = 18.7
if reading < 19.0:
pass # placeholder: decide later what to do with cold readings
print("checked", reading)
Output
checked 18.7

An if statement runs its block when its condition is true. Add elif (“else if”) branches to test more conditions, and an else branch for “none of the above”. Python tests the conditions from top to bottom. It runs the block of the first true condition and skips all the others.

temperature_c = 22.9
if temperature_c < 19.0:
band = "too cold"
elif temperature_c <= 23.0:
band = "normal"
else:
band = "too warm"
print(temperature_c, "->", band)
Output
22.9 -> normal
flowchart TD
    A{"temperature_c < 19.0?"} -- "True" --> B["band = 'too cold'"]
    A -- "False" --> C{"temperature_c <= 23.0?"}
    C -- "True" --> D["band = 'normal'"]
    C -- "False" --> E["band = 'too warm'"]

The second test does not need 19.0 <= temperature_c. Python reaches the elif only when the first test was false, so the reading is already 19.0 or more. Use this to keep conditions short. It also means that the order of the branches matters: put the most specific or the most severe test first.

The rules:

Part How many Runs when
if condition: exactly 1, first its condition is true
elif condition: 0 or more every earlier condition was false and this one is true
else: 0 or 1, last every condition was false

An if without else is fine. It means “do this extra thing, or nothing”.

Sometimes you only need to choose between two values. A conditional expression does this in one line: value_if_true if condition else value_if_false. It is an expression, so it gives a value that you can assign or print.

logins_last_30d = 2
activity = "low" if logins_last_30d <= 3 else "normal"
print(activity)
print(f"{logins_last_30d} login{'' if logins_last_30d == 1 else 's'}")
Output
low
2 logins

Use it for short choices like labels and plural endings. When a branch needs more than one statement, or when there are three or more cases, write a full if statement.

Loops and match work on collections of values. Two collections appear in this module in their simplest form. Module 04 teaches both in depth.

  • A list holds values in order, between square brackets: [21.0, 21.9, 21.4]. len() gives its length, readings[0] gives the first item and readings.append(22.1) adds an item at the end.
  • A dictionary (dict) maps keys to values, between curly braces: {"sensor_id": "S1", "temperature_c": 21.7}. record["sensor_id"] gives the value for a key. Assigning to record["status"] adds or changes a key.
readings = [21.0, 21.9, 21.4]
readings.append(21.7)
record = {"sensor_id": "S1", "temperature_c": 21.7}
record["status"] = "ok"
print(readings, len(readings), readings[0])
print(record["sensor_id"], record)
Output
[21.0, 21.9, 21.4, 21.7] 4 21.0
S1 {'sensor_id': 'S1', 'temperature_c': 21.7, 'status': 'ok'}

A list or a dictionary is a container: an object that holds other objects. A string is a container of characters.

Module 01 showed that every value is truthy or falsy. A condition does not have to be a bool. Python calls bool() on it for you. Empty containers are falsy too:

Falsy Truthy
False, None True
0, 0.0 any other number, also -1 and 0.001
"" (empty string) any non-empty string, also " " and "0"
[] (empty list) a list with at least one item, also [0] and [None]
{} (empty dict) a dict with at least one key
range(0) a range with at least one number

So if readings: means “if the list is not empty”. This is the Pythonic way (the style that experienced Python developers use) to guard a calculation that needs at least one value:

readings = []
if readings:
print("Mean:", sum(readings) / len(readings))
else:
print("No valid readings: cannot compute the mean.")
Output
No valid readings: cannot compute the mean.

Without the guard, sum([]) / len([]) is 0 / 0, which raises a ZeroDivisionError. A guard like this checks a precondition before the code that needs it.

Truthiness has one trap in data work: zero is falsy, but zero is often a real value. A freezer sensor can read 0.0 °C. A new customer can have 0 logins. if not value: treats these real zeros as missing. Test for a missing value with is None:

temperature_c = 0.0 # a real reading from a freezer sensor
if not temperature_c:
print("Truthiness test: reading missing")
if temperature_c is None:
print("None test: reading missing")
else:
print("None test: reading is", temperature_c)
Output
Truthiness test: reading missing
None test: reading is 0.0
You want to know Write Not
Is the value missing? if value is None: if not value: (0 and "" look missing too)
Is a list, dict or string empty? if not items: if len(items) == 0: (works, but longer)
Is a flag set? if has_autopay: if has_autopay == True:
Is a count zero? if count == 0: if not count: (works, but hides the intent)

Short-circuit evaluation. and and or stop as soon as they know the answer. a and b does not evaluate b when a is falsy. a or b does not evaluate b when a is truthy. Use this to protect a calculation:

order_count = 0
total_revenue = 0.0
if order_count > 0 and total_revenue / order_count > 100:
print("High average order value")
else:
print("No orders, or a low average")
Output
No orders, or a low average

order_count > 0 is False, so Python never runs the division, and no ZeroDivisionError occurs.

Both operators return one of their operands, not always a bool. a or b returns a if a is truthy, else b. This gives a common default idiom, with the same zero trap:

coupon_code = ""
print(coupon_code or "NO-COUPON")
discount = 0.0 # a real discount of 0 %
print(discount or 0.1) # wrong: replaces a real 0.0
print(0.1 if discount is None else discount) # right
Output
NO-COUPON
0.1
0.0

An if-elif chain compares one value with many options. It becomes hard to read when the value is a record with structure, such as an API response, and you must check its shape and its values at the same time. The match statement (Python 3.10 and newer) does this with patterns.

  • The subject is the value after match.
  • Each case has a pattern. Python tries the patterns from top to bottom and runs the block of the first one that matches. Later cases are skipped.
  • A pattern can also capture parts of the subject into variables.

The simplest patterns are literals:

status = "warn"
match status:
case "ok":
action = "nothing to do"
case "warn" | "fail":
action = "open a ticket"
case _:
action = f"unknown status {status!r}"
print(action)
Output
open a ticket

"warn" | "fail" is an or-pattern: it matches either value. _ is the wildcard pattern: it matches anything and captures nothing, so it works like else. If no case matches and there is no case _, the match statement does nothing. In the f-string, !r shows the value with repr(), so the quotes are visible.

Patterns become powerful with structured data. A mapping pattern matches a dict that has the given keys. A sequence pattern matches a list with the given shape. A name inside a pattern is a capture pattern: it matches any value and stores it in that variable.

event = {"type": "refund", "order_id": "O000004", "amount": 224.1}
match event:
case {"type": "order", "order_id": order_id}:
print("New order", order_id)
case {"type": "refund", "order_id": order_id, "amount": amount}:
print(f"Refund {amount:.2f} USD for order {order_id}")
case _:
print("Unknown event")
Output
Refund 224.10 USD for order O000004

The second pattern checks three things at once: the subject is a dict, its "type" is "refund", and it has the keys "order_id" and "amount". It then captures both values. A mapping pattern ignores extra keys in the dict.

A guard is an if condition after a pattern: case pattern if condition:. The case matches only when the pattern matches and the guard is true. A class pattern such as float(value) matches only a value of that type and captures it.

Pattern Example Matches
literal case "ok":, case 200:, case None: a value equal to the literal (None, True, False by identity)
or-pattern case "warn" | "fail": any of the alternatives
wildcard case _: anything, captures nothing
capture case value: anything, stores it in value
sequence case ["READ", sensor_id, value]: a list (or tuple) of exactly 3 items whose first item is "READ"
sequence with rest case ["BATCH", sensor_id, *values]: 2 or more items; the extra items go into the list values
mapping case {"status": 429, "retry_after": wait}: a dict with these keys (extra keys are allowed)
class case float(x) | int(x): a value of that type
as-pattern case ("ok" | "warn") as status: the sub-pattern, and stores the matched value
guard case {"status": code} if code >= 500: the pattern, and the condition is true

Use match when you dispatch on the shape of a record or a command. Use if-elif for ranges and thresholds, such as temperature bands.

A for loop runs its block once for each item of a sequence. On each pass, the loop variable refers to the next item. One pass through the block is an iteration. Any object that a for loop can walk through is an iterable: lists, strings, dicts, ranges and files are all iterables.

readings = [21.0, 21.9, 21.4, 21.7]
for reading in readings:
fahrenheit = reading * 9 / 5 + 32
print(f"{reading:.1f} °C = {fahrenheit:.1f} °F")
Output
21.0 °C = 69.8 °F
21.9 °C = 71.4 °F
21.4 °C = 70.5 °F
21.7 °C = 71.1 °F

The loop variable reading gets 21.0, then 21.9, then 21.4, then 21.7. After the last item, the loop ends and the script continues after the block. Choose a singular name for the loop variable and a plural name for the collection: for reading in readings, for customer in customers.

Do not remove items from a list while a for loop walks through it. The loop keeps a position in the list, and removing an item shifts the later items one place to the left, so the loop skips one:

lines = ["21.0", "", "", "21.4"]
for line in lines:
if not line:
lines.remove(line) # wrong: changes the list during the loop
print(lines)
Output
['21.0', '', '21.4']

One empty line survives. Build a new list instead, with the filter pattern below. Module 13 collects this and other common gotchas.

Most loops in data work follow a few loop patterns. The most common is the accumulator: a variable that you set before the loop and update in each iteration, such as a running total or a count.

readings = [21.0, 21.9, 21.4, 21.7, 22.1, 22.0, 22.5, 22.9]
total = 0.0 # accumulator for the sum
warm_count = 0 # accumulator for a count
warm = [] # accumulator for a filtered list
highest = readings[0] # the maximum seen so far
for reading in readings:
total += reading
if reading > 22.0:
warm_count += 1
warm.append(reading)
if reading > highest:
highest = reading
print(f"Mean: {total / len(readings):.2f}")
print("Above 22.0:", warm_count, warm)
print("Highest:", highest)
Output
Mean: 21.94
Above 22.0: 3 [22.1, 22.5, 22.9]
Highest: 22.9
Pattern Before the loop Inside the loop Built-in shortcut
sum total = 0 total += x sum(xs)
count count = 0 if test: count += 1 sum(1 for x in xs if test) (module 04)
filter kept = [] if test: kept.append(x) list comprehension (module 04)
maximum highest = xs[0] if x > highest: highest = x max(xs)
search found = None if test: found = x then break next(...) (module 10)

Use the built-in shortcut when one exists. Write the loop when you need several results in one pass, or a rule that no built-in covers.

range() produces a sequence of whole numbers. It does not build a list in memory; it computes each number when the loop asks for it. list(range(...)) shows the numbers.

Call Numbers Use
range(5) 0, 1, 2, 3, 4 repeat 5 times
range(1, 6) 1, 2, 3, 4, 5 epochs or days numbered from 1
range(0, 60, 10) 0, 10, 20, 30, 40, 50 a 10-minute reading schedule
range(5, 0, -1) 5, 4, 3, 2, 1 count down
print(list(range(5)))
print(list(range(0, 60, 10)))
for epoch in range(1, 4):
print("Training epoch", epoch, "of 3")
Output
[0, 1, 2, 3, 4]
[0, 10, 20, 30, 40, 50]
Training epoch 1 of 3
Training epoch 2 of 3
Training epoch 3 of 3

The stop value is not included. range(0, 60, 10) stops before 60. This is a half-open interval: it includes the start and excludes the stop. It has two useful properties. range(n) has exactly n numbers. And two ranges join without overlap: range(0, 6) and range(6, 12) cover 0 to 11. Slices of strings and lists follow the same rule.

An epoch in machine learning is one full pass of a training algorithm over the training data. Training loops in PyTorch (module 42) start with for epoch in range(n_epochs):.

When the loop variable is not used, name it _. This tells the reader, and linters, that the value is ignored: for _ in range(3):.

Often you need the position of each item too, for example a line number for an error message. enumerate() gives pairs of (position, item). start=1 numbers the items from 1, as editors number lines.

lines = ["21.0", "21.9", "error", "21.4"]
for line_number, line in enumerate(lines, start=1):
print(line_number, line)
Output
1 21.0
2 21.9
3 error
4 21.4

for line_number, line in ... takes each pair apart into two variables. This is called unpacking. Module 04 covers it in full.

Avoid for i in range(len(lines)): followed by lines[i]. It works, but it is longer and easier to get wrong. enumerate() says what you mean.

zip(): loop over several sequences together

Section titled “zip(): loop over several sequences together”

Data often arrives as parallel lists: lists of the same length where position i in each list describes the same thing. zip() walks through them together and gives one tuple per position. A tuple (module 01) is a fixed group of values in parentheses, such as ("S1", 21.7). Module 04 covers tuples in depth.

sensor_ids = ["S1", "S2", "S3", "S4"]
temperatures = [20.21, 22.30, 19.40, 24.52]
for sensor_id, temperature in zip(sensor_ids, temperatures, strict=True):
print(f"{sensor_id}: {temperature:.1f} °C")
Output
S1: 20.2 °C
S2: 22.3 °C
S3: 19.4 °C
S4: 24.5 °C

By default, zip() stops at the end of the shortest input and drops the extra items without a word. When the lists must have the same length, pass strict=True (Python 3.10 and newer). Then a length mismatch raises a ValueError instead of hiding a data bug:

sensor_ids = ["S1", "S2", "S3", "S4"]
temperatures = [20.21, 22.30, 19.40] # one value is missing
for sensor_id, temperature in zip(sensor_ids, temperatures, strict=True):
print(sensor_id, temperature)
Output
S1 20.21
S2 22.3
S3 19.4
ValueError: zip() argument 2 is shorter than argument 1

The loop prints three pairs. Then zip() finds that the first list has one more item and raises the error.

A for loop runs once per item, so you know the number of iterations in advance. A while loop runs as long as its condition is true. Use it when you do not know how many iterations you need: retry until a request succeeds, train until the error is small enough, wait until a value crosses a limit.

users = 1200.0 # monthly active users today
months = 0
while users < 5000:
users *= 1.08 # 8 % growth per month
months += 1
print(f"{months} months to reach {users:,.0f} users")
Output
19 months to reach 5,179 users

Python checks the condition before each iteration. When it is false, the loop ends. Something inside the loop must change the condition. Otherwise the loop never ends. This is an infinite loop. Stop a script that hangs with Ctrl+C in the terminal.

Two statements change the flow inside a loop:

  • continue ends the current iteration at once and jumps to the next one. Use it to skip an item, such as an invalid line.
  • break ends the whole loop at once. Use it to stop early, such as at the first failure or when you found what you need.
lines = ["21.0", "", "21.9", "n/a", "38.5", "21.4"]
for line in lines:
if not line:
continue # skip empty lines
if line == "n/a":
print("Skipped a missing value")
continue
value = float(line)
if value > 30.0:
print("Sensor fault:", value, "- stopping")
break
print("OK:", value)
Output
OK: 21.0
OK: 21.9
Skipped a missing value
Sensor fault: 38.5 - stopping

The empty line is falsy, so continue skips it. "n/a" is skipped too. The value 38.5 triggers break, so the last line, "21.4", never runs. This style, where each special case leaves early, keeps the main code flat and readable.

In nested loops (a loop inside a loop), break and continue act only on the innermost loop.

A for or while loop can have an else block. It runs when the loop ends normally, that is, without break. This fits one job very well: a search that must report when it finds nothing.

stock_levels = [("P001", 92), ("P002", 151), ("P006", 0), ("P019", 0)]
for product_id, stock in stock_levels:
if stock == 0:
print("First out-of-stock product:", product_id)
break
else:
print("All products are in stock.")
Output
First out-of-stock product: P006
flowchart TD
    A["Next item"] --> B{"Item found?"}
    B -- "yes" --> C["break"]
    B -- "no" --> D{"More items?"}
    D -- "yes" --> A
    D -- "no" --> E["else block: not found"]
    C --> F["Code after the loop"]
    E --> F

Read the else of a loop as “no break”. The name confuses many developers, so add a comment, such as # no break: nothing found, when you use it. The else belongs to the loop, so it lines up with for, not with the if inside.

Example 1 — Classify sensor rows by status

Section titled “Example 1 — Classify sensor rows by status”

Goal: data/sensors.csv marks each reading ok, warn or fail by a rule from the maintenance team: fail if vibration ≥ 11.2 mm/s or temperature ≥ 42 °C, warn if vibration ≥ 4.5 mm/s or temperature ≥ 33 °C, else ok. Apply the rule to six real rows, one of which has no temperature, and count the results.

temperature_c = 24.88
vibration_mm_s = 12.92
if vibration_mm_s >= 11.2 or temperature_c >= 42:
status = "fail"
elif vibration_mm_s >= 4.5 or temperature_c >= 33:
status = "warn"
else:
status = "ok"
print(status)
Output
fail

This is sensor S4 at 2024-05-01 08:00. Its temperature is normal, but its vibration is above the fail limit. or makes either problem enough. The fail test comes first because it is the most severe.

Step 2 — See why the order of the branches matters

Section titled “Step 2 — See why the order of the branches matters”
if vibration_mm_s >= 4.5 or temperature_c >= 33:
wrong_status = "warn"
elif vibration_mm_s >= 11.2 or temperature_c >= 42:
wrong_status = "fail"
else:
wrong_status = "ok"
print(wrong_status)
Output
warn

Every value that passes the fail limit also passes the warn limit. With the warn test first, Python takes that branch and never reaches the fail test. The fail branch can never run. Order the branches from the most severe or the most specific to the least.

Step 3 — Classify every row and handle a missing value

Section titled “Step 3 — Classify every row and handle a missing value”
rows = [
{"sensor_id": "S1", "temperature_c": 20.21, "vibration_mm_s": 2.50},
{"sensor_id": "S2", "temperature_c": 38.03, "vibration_mm_s": 2.39},
{"sensor_id": "S2", "temperature_c": None, "vibration_mm_s": 2.93},
{"sensor_id": "S4", "temperature_c": 24.88, "vibration_mm_s": 12.92},
{"sensor_id": "S2", "temperature_c": 44.89, "vibration_mm_s": 2.96},
{"sensor_id": "S4", "temperature_c": 28.34, "vibration_mm_s": 4.50},
]
for row in rows:
temperature_c = row["temperature_c"]
vibration_mm_s = row["vibration_mm_s"]
if temperature_c is None:
status = "incomplete"
elif vibration_mm_s >= 11.2 or temperature_c >= 42:
status = "fail"
elif vibration_mm_s >= 4.5 or temperature_c >= 33:
status = "warn"
else:
status = "ok"
row["status"] = status
print(row["sensor_id"], temperature_c, vibration_mm_s, status)
Output
S1 20.21 2.5 ok
S2 38.03 2.39 warn
S2 None 2.93 incomplete
S4 24.88 12.92 fail
S2 44.89 2.96 fail
S4 28.34 4.5 warn

The third row has a blank temperature, stored as None. The is None test comes first. Without it, None >= 42 would raise a TypeError. The last row has a vibration of exactly 4.50, and >= includes the limit, so it is warn. The loop also stores the result in each record with row["status"] = status.

counts = {"ok": 0, "warn": 0, "fail": 0, "incomplete": 0}
for row in rows:
counts[row["status"]] += 1
print(counts)
Output
{'ok': 1, 'warn': 2, 'fail': 2, 'incomplete': 1}

The dict holds one counter per status. counts[row["status"]] += 1 finds the right counter by key and adds 1. Module 09 shows collections.Counter, which does this in one line.

Common mistakes:

  • Testing the mild condition before the severe one. The severe branch then never runs, and no error tells you.
  • Comparing before checking for None. A blank value in one row crashes the whole loop with a TypeError.
  • Writing vibration_mm_s >= 4.5 or 33 instead of repeating the variable: ... or temperature_c >= 33.
  • Using > where the rule says “at or above”. Boundary values such as 4.50 then get the wrong label.

Goal: data/readings.txt has one temperature per line. Three lines are broken: error, an empty line and n/a. Read the file, skip the broken lines, report their line numbers and compute the mean of the valid readings.

from pathlib import Path
lines = Path("data/readings.txt").read_text(encoding="utf-8").splitlines()
print(len(lines), "lines")
print(lines[:5])
Output
43 lines
['21.0', '21.9', '21.4', '21.7', '22.1']

The second line reads the whole file and splits it into a list of strings, one per line. Module 07 explains files in detail. For now, read it as “give me the lines of the file”. lines[:5] is a slice: the first 5 items, as with strings in module 02.

for line_number, line in enumerate(lines, start=1):
text = line.strip()
if not text:
print(f"line {line_number}: empty")
elif not text.replace(".", "", 1).isdigit():
print(f"line {line_number}: not a number: {text!r}")
Output
line 12: not a number: 'error'
line 24: empty
line 35: not a number: 'n/a'

enumerate(lines, start=1) gives the line numbers that an editor shows. An empty string is falsy, so not text finds the empty line. text.replace(".", "", 1) removes one decimal point, so "21.7" becomes "217", and .isdigit() is true only for digits. This check accepts the positive decimal numbers of this file. Module 06 shows the general way: try float() and catch the ValueError.

readings = []
skipped = 0
for line in lines:
text = line.strip()
if not text or not text.replace(".", "", 1).isdigit():
skipped += 1
continue
readings.append(float(text))
print("valid:", len(readings), "skipped:", skipped)
print(readings[:5])
Output
valid: 40 skipped: 3
[21.0, 21.9, 21.4, 21.7, 22.1]

Each broken line takes the continue exit, so float() only ever sees valid text. Short-circuit evaluation protects the second test: for an empty line, not text is already true, and Python does not evaluate the rest. The valid count and the skipped count add up to 43.

if readings:
mean = sum(readings) / len(readings)
print(f"Mean of {len(readings)} readings: {mean:.2f} °C")
print(f"Min {min(readings)} °C, max {max(readings)} °C")
else:
print("No valid readings.")
Output
Mean of 40 readings: 21.06 °C
Min 19.3 °C, max 22.9 °C

if readings: is the guard. A file with only broken lines gives an empty list, and the else branch reports it instead of crashing with a ZeroDivisionError. sum(), min() and max() accept a list.

Common mistakes:

  • Calling float(line) before checking the line. The first broken line stops the script with a ValueError.
  • Forgetting .strip(). A line with only spaces is truthy, because a space is a character.
  • Writing if not text.replace(".", "").isdigit() without the 1. Then "21.7.3" passes the check and float() fails later.
  • Using range(len(lines)) and lines[i]. enumerate() gives the number and the line with less code.

Goal: Six order lines from data/sales.csv arrive as parallel lists: products, unit prices, quantities and discounts. Compute each line’s revenue, label its discount, flag bulk lines and check the total against the file.

products = [
"Cotton Bed Sheet Set",
"Noise-Cancelling Headphones",
"14-inch Ultrabook Laptop",
"Weeknight Kitchen Cookbook",
"Hydrating Face Cream",
"Statistics Made Simple",
]
unit_prices = [69.99, 249.00, 1149.00, 29.99, 32.00, 34.99]
quantities = [1, 1, 2, 1, 12, 20]
discounts = [0.05, 0.1, 0.05, 0.2, 0.1, 0.0]
for product, price, quantity in zip(products, unit_prices, quantities, strict=True):
print(f"{quantity:>2} x {product} @ {price:.2f} USD")
Output
1 x Cotton Bed Sheet Set @ 69.99 USD
1 x Noise-Cancelling Headphones @ 249.00 USD
2 x 14-inch Ultrabook Laptop @ 1149.00 USD
1 x Weeknight Kitchen Cookbook @ 29.99 USD
12 x Hydrating Face Cream @ 32.00 USD
20 x Statistics Made Simple @ 34.99 USD

zip() takes any number of iterables. Each iteration unpacks one value from each list. strict=True guarantees that every product has a price and a quantity. The format spec :>2 right-aligns the quantity in 2 characters.

Step 2 — Compute the revenue and label the discount

Section titled “Step 2 — Compute the revenue and label the discount”
total = 0.0
for product, price, quantity, discount in zip(
products, unit_prices, quantities, discounts, strict=True
):
revenue = round(price * quantity * (1 - discount), 2)
total += revenue
if discount == 0:
label = "full price"
elif discount < 0.2:
label = "standard"
else:
label = "promo"
print(f"{product:<28} {revenue:>8.2f} {label}")
print(f"{'Total':<28} {total:>8.2f}")
Output
Cotton Bed Sheet Set 66.49 standard
Noise-Cancelling Headphones 224.10 standard
14-inch Ultrabook Laptop 2183.10 standard
Weeknight Kitchen Cookbook 23.99 promo
Hydrating Face Cream 345.60 standard
Statistics Made Simple 699.80 full price
Total 3543.08

The revenue formula is the one that data/sales.csv uses. total is an accumulator. The if chain turns the four discount levels of the dataset (0, 0.05, 0.1 and 0.2) into three labels. :<28 left-aligns the name in 28 characters, so the numbers line up.

Step 3 — Flag bulk lines with a conditional expression

Section titled “Step 3 — Flag bulk lines with a conditional expression”
for product, quantity in zip(products, quantities, strict=True):
size = "bulk" if quantity >= 10 else "regular"
print(f"{product:<28} {quantity:>3} {size}")
Output
Cotton Bed Sheet Set 1 regular
Noise-Cancelling Headphones 1 regular
14-inch Ultrabook Laptop 2 regular
Weeknight Kitchen Cookbook 1 regular
Hydrating Face Cream 12 bulk
Statistics Made Simple 20 bulk

The dataset has 29 bulk lines with 10 to 25 units. A two-way label is a good use of a conditional expression: one line, one clear choice.

Step 4 — Check the total against the file

Section titled “Step 4 — Check the total against the file”
import math
file_revenues = [66.49, 224.1, 2183.1, 23.99, 345.6, 699.8]
file_total = sum(file_revenues)
print(round(file_total, 2), math.isclose(total, file_total))
Output
3543.08 True

The total matches the revenue column of the file. A check like this at the end of a pipeline step catches a wrong formula or a lost line. math.isclose() compares the float sums safely.

Common mistakes:

  • Leaving out strict=True. If one list is one item short, zip() silently drops the last line and the total is wrong.
  • Testing discount < 0.2 before discount == 0. A zero discount is also less than 0.2, so it gets the wrong label.
  • Using range(len(products)) and indexing four lists. Every index is a chance for a typo; zip() has none.

Example 4 — Route API responses with match-case

Section titled “Example 4 — Route API responses with match-case”

Goal: A script downloads product pages from the course’s sample API. Each response is a dict. Its shape depends on the result: data, an empty page, a rate limit or an error. Decide for each response what the script does next.

response = {
"status": 429,
"error": "rate_limit_exceeded",
"message": "Too many requests. Limit is 60 requests per minute.",
"retry_after": 30,
}
match response["status"]:
case 200:
print("Success")
case 429:
print("Rate limited")
case 500 | 502 | 503:
print("Server error")
case _:
print("Other status:", response["status"])
Output
Rate limited

This is the content of data/api/error_429.json, shortened. An HTTP status code is the number a web server returns with each response: 200 means success, 429 means “too many requests” and 5xx codes mean a server error. Literal patterns and an or-pattern route the code. This is no better than if-elif yet.

Step 2 — Capture fields with a mapping pattern

Section titled “Step 2 — Capture fields with a mapping pattern”
match response:
case {"status": 429, "retry_after": int(seconds)}:
print(f"Rate limited: wait {seconds} s, then retry")
case {"status": 200, "data": items}:
print("Got", len(items), "items")
case _:
print("Unexpected response")
Output
Rate limited: wait 30 s, then retry

Now the pattern checks the status and the shape together. It matches only when the dict has a "retry_after" key whose value is an int, and it captures that value in seconds. A 429 response without "retry_after" would fall through to case _ instead of crashing with a KeyError.

Step 3 — Route every response with guards

Section titled “Step 3 — Route every response with guards”
responses = [
{"status": 200, "data": [{"id": "P001"}, {"id": "P002"}], "next": "page=2"},
{"status": 200, "data": [{"id": "P021"}, {"id": "P022"}], "next": None},
{"status": 200, "data": [], "next": None},
{"status": 429, "error": "rate_limit_exceeded", "retry_after": 30},
{"status": 503, "error": "service_unavailable"},
{"status": 404, "error": "not_found"},
{"detail": "timeout"},
]
for response in responses:
match response:
case {"status": 200, "data": []}:
action = "empty page: stop"
case {"status": 200, "data": [first, *rest], "next": None}:
action = f"last page: {1 + len(rest)} items from {first['id']}"
case {"status": 200, "data": [first, *rest]}:
action = f"{1 + len(rest)} items from {first['id']}: fetch next page"
case {"status": 429, "retry_after": int(seconds)}:
action = f"wait {seconds} s and retry"
case {"status": int(code), "error": str(error)} if code >= 500:
action = f"server error {code} ({error}): retry later"
case {"status": int(code), "error": str(error)}:
action = f"client error {code} ({error}): give up"
case _:
action = "unknown response shape: log it"
print(action)
Output
2 items from P001: fetch next page
last page: 2 items from P021
empty page: stop
wait 30 s and retry
server error 503 (service_unavailable): retry later
client error 404 (not_found): give up
unknown response shape: log it

Each case reads like a line of a specification. [] matches an empty list. [first, *rest] matches a list with at least one item: first captures the first item and rest collects the others. The guard if code >= 500 splits errors into “retry” and “give up”. The order matters: the empty-page and last-page cases come before the general data case, and the guarded case comes before the unguarded one.

Common mistakes:

  • Putting case {"status": 200, "data": items} first. It also matches empty and last pages, so the specific cases never run.
  • Expecting a mapping pattern to require an exact set of keys. It ignores extra keys. Use **rest in the pattern to capture them if you need to check.
  • Writing case {"status": OK_STATUS} with a variable. A bare name in a pattern captures; it does not compare. Use a literal or a guard.
  • Forgetting case _. A response with an unexpected shape then passes silently, and action keeps its value from the previous iteration.

Example 5 — Parse sensor gateway messages with sequence patterns

Section titled “Example 5 — Parse sensor gateway messages with sequence patterns”

Goal: A sensor gateway sends one text command per line, such as READ S1 20.21 or BATCH S2 22.30 22.44 22.25. Parse each message by its shape, collect the valid readings and report the problems.

message = "BATCH S2 22.30 22.44 22.25"
words = message.split()
print(words)
print(len(words), "words, command", words[0])
Output
['BATCH', 'S2', '22.30', '22.44', '22.25']
5 words, command BATCH

.split() with no argument splits on runs of whitespace and returns a list of words. The first word is the command. The number of words depends on the command, which is exactly the job of sequence patterns.

match words:
case ["READ", sensor_id, value]:
print("one reading from", sensor_id, value)
case ["BATCH", sensor_id, *values]:
print(len(values), "readings from", sensor_id, values)
case _:
print("unknown message")
Output
3 readings from S2 ['22.30', '22.44', '22.25']

["READ", sensor_id, value] matches a list of exactly 3 words that starts with "READ". ["BATCH", sensor_id, *values] matches 2 or more words; *values collects all the extra words into a list. A sequence pattern never matches a plain string, so you must split first.

messages = [
"READ S1 20.21",
"READ S3 n/a",
"BATCH S2 22.30 22.44 22.25",
"BATCH S4",
"STATUS S4 warn",
"STATUS S1 broken",
"PING",
"",
"RESET S2 now",
]
readings = []
for message in messages:
match message.split():
case ["READ", sensor_id, value] if value.replace(".", "", 1).isdigit():
readings.append(float(value))
print(f"{sensor_id}: reading {value}")
case ["READ", sensor_id, value]:
print(f"{sensor_id}: invalid value {value!r}")
case ["BATCH", sensor_id, *values] if values:
for value in values:
readings.append(float(value))
print(f"{sensor_id}: batch of {len(values)}")
case ["BATCH", sensor_id]:
print(f"{sensor_id}: empty batch")
case ["STATUS", sensor_id, ("ok" | "warn" | "fail") as status]:
print(f"{sensor_id}: status {status}")
case ["STATUS", sensor_id, other]:
print(f"{sensor_id}: invalid status {other!r}")
case ["PING"]:
print("gateway alive")
case []:
print("empty line skipped")
case [command, *_]:
print(f"unknown command {command!r} in {message!r}")
print("valid readings:", readings)
Output
S1: reading 20.21
S3: invalid value 'n/a'
S2: batch of 3
S4: empty batch
S4: status warn
S1: invalid status 'broken'
gateway alive
empty line skipped
unknown command 'RESET' in 'RESET S2 now'
valid readings: [20.21, 22.3, 22.44, 22.25]

The guard on the first case accepts only numeric values, so READ S3 n/a falls to the second case. BATCH S4 matches the BATCH pattern with an empty values list, but the guard if values is false, so Python moves on to the next case, which handles the empty batch. ("ok" | "warn" | "fail") as status accepts only the three known statuses and captures which one it was. Any other status word falls to the next case, which reports it as invalid. The empty message splits into [], and [command, *_] catches every other command.

Common mistakes:

  • Matching the string itself: case ["PING"] never matches "PING". Match message.split().
  • Forgetting that *values can be empty. Add a guard such as if values when at least one item is required.
  • Placing case [command, *_] before the specific cases. It matches every non-empty message, so the specific cases never run.

Example 6 — Find the first at-risk customer with loop else

Section titled “Example 6 — Find the first at-risk customer with loop else”

Goal: The retention team calls customers who are likely to churn. In data/customers.csv, customers with tenure of 6 months or less and 3 logins or fewer in 30 days churn far more often. Find the first such customer in a batch, and report clearly when there is none.

customers = [
{"customer_id": "C04339", "tenure_months": 4, "logins_last_30d": 13,
"contract": "one-year"},
{"customer_id": "C04557", "tenure_months": 2, "logins_last_30d": 37,
"contract": "one-year"},
{"customer_id": "C03439", "tenure_months": 9, "logins_last_30d": 5,
"contract": "one-year"},
{"customer_id": "C03991", "tenure_months": 6, "logins_last_30d": 2,
"contract": "month-to-month"},
{"customer_id": "C04007", "tenure_months": 6, "logins_last_30d": 2,
"contract": "one-year"},
]
print(len(customers), "customers")
Output
5 customers

These are five real rows from the dataset, with four of their columns. A list of dicts is the simplest form of a table in plain Python: one dict per row, one key per column.

for customer in customers:
if customer["tenure_months"] <= 6 and customer["logins_last_30d"] <= 3:
print("Call first:", customer["customer_id"])
break
else: # no break: nobody matched
print("No at-risk customer in this batch.")
Output
Call first: C03991

The loop checks each customer in order. C03991 is the first one that matches both rules, so the loop prints its id and breaks. The else block is skipped because the loop ended with break. C04007 also matches, but the search stopped before it.

Step 3 — Run a search that finds nothing

Section titled “Step 3 — Run a search that finds nothing”
for customer in customers:
if customer["tenure_months"] <= 3 and customer["logins_last_30d"] <= 3:
print("Call first:", customer["customer_id"])
break
else: # no break: nobody matched
print("No at-risk customer in this batch.")
Output
No at-risk customer in this batch.

With a stricter tenure limit, no customer matches. The loop runs to the end without break, so the else block runs. Without loop else, you need an extra variable, as the next step shows.

found = None
for customer in customers:
if customer["tenure_months"] <= 6 and customer["logins_last_30d"] <= 3:
found = customer
break
if found is None:
print("No at-risk customer in this batch.")
else:
print("Call first:", found["customer_id"], found["contract"])
Output
Call first: C03991 month-to-month

The flag variable found starts as None and holds the match after the loop. This version is longer, but it keeps the found record for later code. Use loop else when you only act inside the loop. Use a flag variable when you need the result afterwards.

Common mistakes:

  • Indenting else under the if. Then it runs for every customer that does not match, and prints “No at-risk customer” several times.
  • Forgetting break. Without it, the else block always runs, even when a customer matched.
  • Testing if not found: when a valid result could be falsy, such as a count of 0. Test if found is None:.

Example 7 — Train a model until it converges

Section titled “Example 7 — Train a model until it converges”

Goal: Fit the simplest model in machine learning: price = w × size, for four houses. Find the weight w with gradient descent, an algorithm that improves a guess step by step. Stop when the steps become tiny, with a limit on the number of iterations.

Step 1 — Store the data and define the error

Section titled “Step 1 — Store the data and define the error”
sizes = [0.8, 1.2, 1.5, 2.0] # floor area in 100 m²
prices = [2.5, 3.5, 4.6, 6.1] # price in 100,000 USD
w = 0.0 # first guess for the weight
squared_error = 0.0
for size, price in zip(sizes, prices, strict=True):
squared_error += (w * size - price) ** 2
print(f"MSE at w = {w}: {squared_error / len(sizes):.3f}")
Output
MSE at w = 0.0: 19.217

The mean squared error (MSE) measures how wrong the model is: the average of the squared differences between prediction and truth. With w = 0, every prediction is 0, so the error is large.

MSE(w)=1n∑i=1n(wxi−yi)2d MSEdw=2n∑i=1n(wxi−yi) xi\text{MSE}(w) = \frac{1}{n}\sum_{i=1}^{n}(w x_i - y_i)^2 \qquad \frac{d\,\text{MSE}}{dw} = \frac{2}{n}\sum_{i=1}^{n}(w x_i - y_i)\,x_i

The second formula is the gradient: the slope of the error at the current w. Moving w against the slope lowers the error. Module 32 explains the math. Here it is just a formula that a loop computes.

learning_rate = 0.1
tolerance = 1e-6
max_iter = 1000
iteration = 0
while iteration < max_iter:
gradient = 0.0
for size, price in zip(sizes, prices, strict=True):
gradient += 2 * (w * size - price) * size
gradient /= len(sizes)
step = learning_rate * gradient
w -= step
iteration += 1
if abs(step) < tolerance:
print(f"Converged after {iteration} iterations: w = {w:.4f}")
break
else: # no break: the limit was reached
print(f"No convergence after {max_iter} iterations: w = {w:.4f}")
Output
Converged after 28 iterations: w = 3.0372

Each iteration computes the gradient with an inner for loop, then moves w one small step downhill. The learning rate sets the size of the step. Convergence means that the steps have become so small that more iterations would not change the answer. The break ends the training then. The max_iter limit and the loop else handle the case where training does not converge.

Step 3 — Watch a learning rate that is too large

Section titled “Step 3 — Watch a learning rate that is too large”
w = 0.0
learning_rate = 0.6
for iteration in range(1, 6):
gradient = 0.0
for size, price in zip(sizes, prices, strict=True):
gradient += 2 * (w * size - price) * size
gradient /= len(sizes)
w -= learning_rate * gradient
print(f"iteration {iteration}: w = {w:,.1f}")
Output
iteration 1: w = 7.6
iteration 2: w = -3.8
iteration 3: w = 13.3
iteration 4: w = -12.3
iteration 5: w = 26.0

With a learning rate of 0.6, each step overshoots the minimum by more than the previous error. w swings from side to side and grows without limit. This is divergence. In a while loop without max_iter, the script would never stop. The max_iter limit ends the loop, but it only reports “no convergence”. A divergence check such as abs(w) > 1e6, as in exercise M03-X03, names the real problem.

Common mistakes:

  • Writing while True: without a limit. A diverging model then runs forever.
  • Forgetting to reset gradient = 0.0 at the start of each iteration. The gradient then keeps the sums of earlier iterations.
  • Comparing step < tolerance without abs(). The first step is negative here (w goes up), so step < tolerance is true at once and the loop stops after one iteration.
Mistake Symptom Fix
A missing colon after if, for, while or case SyntaxError: expected ':' End the line with :
Wrong or mixed indentation IndentationError Indent every block line by 4 spaces; never mix tabs and spaces
The mild condition before the severe one in an if-elif chain The severe branch never runs Order from most specific or severe to least
if not value: for a missing value Real zeros (0.0 °C, 0 logins) are treated as missing if value is None:
x or default with a valid 0 A real 0 is replaced by the default default if x is None else x
if x == 1 or 2: Always true if x == 1 or x == 2: or if x in (1, 2):
Comparing None with a number TypeError: '>=' not supported between instances of 'NoneType' and 'int' Test is None first
Averaging an empty list ZeroDivisionError: division by zero Guard with if readings:
zip() on lists of different lengths Items are dropped silently zip(..., strict=True)
Expecting range(0, 60, 10) to include 60 The last value is 50 The stop is excluded; use range(0, 61, 10)
for i in range(len(xs)): with xs[i] Longer code, off-by-one bugs for x in xs: or enumerate(xs)
A while loop whose condition never changes The script hangs Update the condition in the loop; add a max_iter limit; stop with Ctrl+C
Loop else indented under the if The message prints for every non-matching item Align else with for
A break that never runs, with a loop else The “not found” message always prints Check the search condition
case limit: to compare with a variable Matches everything; SyntaxError if not last Use a literal or a guard: case x if x == limit:
A general case before specific ones The specific cases never run Order cases from specific to general
Changing a list while you loop over it Items are skipped Build a new list (filter pattern)
  • Web development: a request handler uses match on the method and path, such as case ("GET", ["products", product_id]):, and if checks for login and permissions before it runs.
  • Automation: a backup script retries a failed upload in a while loop with a growing wait (1, 2, then 4 seconds) and gives up after 3 attempts. A deployment script stops at the first failed health check with break.
  • Command-line tools: a CLI matches sys.argv[1:] (the command-line words after the script name) against patterns such as ["add", name] and ["list"], the same way Example 5 parses gateway messages.
  • Tooling: a linter loops over the lines of a file with enumerate(lines, start=1) and reports each problem with its line number.
  • Control flow changes the order of statements. Branches (if, match) decide; loops (for, while) repeat.
  • A block starts after a colon and is indented by 4 spaces.
  • if-elif-else runs only the first true branch. Order the branches from the most specific to the least.
  • A conditional expression, a if condition else b, chooses between two values.
  • Empty strings, lists and dicts, 0 and None are falsy. Use if items: for “not empty” and is None for “missing”.
  • and and or short-circuit. Use them to guard a risky operation.
  • match compares a subject with patterns: literals, |, _, captures, sequences, mappings, classes and guards. The first matching case wins.
  • for loops over any iterable. range() gives numbers (the stop is excluded), enumerate() adds positions and zip(..., strict=True) pairs parallel sequences.
  • while loops until a condition is false. Always make sure the loop can end.
  • continue skips to the next item. break stops the loop. A loop else runs only when the loop did not break: use it for “not found”.

Q1. reading = 30.0. Which branch runs, and why?

if reading > 20:
print("warm")
elif reading > 25:
print("hot")
else:
print("cold")
Answer

warm. Python tests the conditions in order and runs only the first true branch. 30.0 > 20 is true, so the elif is never tested. Put the stricter test (> 25) first.

Q2. What does bool([]), bool([0]) and bool({}) give?

Answer

False, True and False. An empty container is falsy. [0] holds one item, so it is not empty and is truthy, even though the item itself is falsy.

Q3. A field avg_session_minutes can be None (not logged) or a number, including 0.0. Why is if not avg_session_minutes: the wrong test for “not logged”?

Answer

0.0 is falsy, so a real session time of zero would look “not logged”. Write if avg_session_minutes is None:.

Q4. What does list(range(2, 11, 3)) give?

Answer

[2, 5, 8]. It starts at 2 and adds 3 each time. 11 would be the next value, and the stop value is excluded.

Q5. zip(["S1", "S2", "S3"], [21.7, 22.0]) produces how many pairs? How do you make this mismatch an error?

Answer

Two pairs: ("S1", 21.7) and ("S2", 22.0). zip() stops at the shortest input and drops "S3". Pass strict=True to raise a ValueError instead.

Q6. When does the else block of a for loop run?

Answer

When the loop finishes without break: it went through all items, or the iterable was empty. It does not run when break ended the loop. Read it as “no break”.

Q7. What is the difference between break and continue?

Answer

continue ends the current iteration and goes on with the next item. break ends the whole loop. Use continue to skip a bad row and break to stop at the first fatal problem or after a search succeeds.

Q8. Does case {"status": 200}: match the dict {"status": 200, "data": [], "next": None}?

Answer

Yes. A mapping pattern requires only the keys it names. Extra keys are ignored.

Q9. What does case ["BATCH", sensor_id, *values]: match, and what is values for the words ["BATCH", "S4"]?

Answer

It matches any list (or tuple) of 2 or more items whose first item is "BATCH". For ["BATCH", "S4"], sensor_id is "S4" and values is the empty list []. Add the guard if values to require at least one value.

Q10. When should you choose a while loop over a for loop?

Answer

When you do not know the number of iterations in advance: retry until success, train until convergence, grow until a limit. When you loop over the items of a collection or a fixed count, use for. A while loop needs a condition that eventually becomes false, ideally with a maximum number of iterations.

Q11. Why does order_count > 0 and total / order_count > 100 never raise a ZeroDivisionError?

Answer

and short-circuits. When order_count > 0 is false, Python already knows the result is false and never evaluates the division.

Your progress

0 / 4 done

  • Exercises: 26 exercises on branches, truthiness, match-case and loops, with hints and full solutions.
  • Mini-project: build a quality report for the raw sensor log.
  • Cheat sheet: every statement, pattern and loop idiom of this module on one page.
  • Next module: 04. Data structures teaches lists, tuples, dicts and sets in depth, with comprehensions that replace many of the loops in this module.