Skip to content

03. Control flow — Exercises

These exercises practice every idea of the control flow lesson. They use the course datasets: sensor readings, order lines from data/sales.csv, customer records from data/customers.csv and API responses from data/api/.

How to work:

  1. Read the task and the expected output (or the acceptance criteria).
  2. Copy the starter code into a script, for example exercise.py, and replace each to-do comment with your code.
  3. Run it with python exercise.py from your project folder, so that data/ is found. Compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Each solution ends with assert checks. Add the same checks to your own code.

Warm-up

The server room is too cold below 19.0 °C, normal from 19.0 to 23.0 °C (both included) and too warm above 23.0 °C. Label each of the three readings and print one line per reading.

Expected output
18.7 °C: too cold
23.0 °C: normal
23.6 °C: too warm
Starter
readings = [18.7, 23.0, 23.6]
for reading in readings:
# TODO: choose the label with if, elif and else
# TODO: print the reading and its label
pass
Hint 1

Test reading < 19.0 first. In the elif, you only need the upper limit: reading <= 23.0.

Hint 2

23.0 itself is normal, so the second test must use <=, not <.

Solution
readings = [18.7, 23.0, 23.6]
labels = []
for reading in readings:
if reading < 19.0:
label = "too cold"
elif reading <= 23.0:
label = "normal"
else:
label = "too warm"
labels.append(label)
print(f"{reading} °C: {label}")
assert labels == ["too cold", "normal", "too warm"]
Output
18.7 °C: too cold
23.0 °C: normal
23.6 °C: too warm

How it works:

  1. The loop gives each reading to the if chain in turn.
  2. Python reaches the elif only when the reading is 19.0 or more, so reading <= 23.0 is enough for the “normal” band.
  3. The boundary value 23.0 passes <= 23.0, so it is normal.
  4. The solution also collects the labels in a list, so the assert can check all three at once.

Alternative: a chained comparison makes each band explicit: elif 19.0 <= reading <= 23.0:. It is longer, but each branch can be read on its own.

M03-W02 · Predict the output: truthiness of containers

Section titled “M03-W02 · Predict the output: truthiness of containers”
Warm-up

Predict the output: for each value, decide whether bool() gives True or False.

Acceptance criteria:

  • Write your prediction for the 8 values, then run the code.
  • Your prediction matches the Output in the solution.
Starter
print(bool([]), bool([0]), bool({}), bool({"churned": 0}))
print(bool(""), bool(" "), bool(None), bool(0.0))
# TODO: write your prediction for each value before you run the code
Hint 1

An empty container is falsy. A container with at least one item is truthy, whatever the item is.

Hint 2

A space is a character, so " " is not empty.

Solution
print(bool([]), bool([0]), bool({}), bool({"churned": 0}))
print(bool(""), bool(" "), bool(None), bool(0.0))
assert not [] and [0]
assert not {} and {"churned": 0}
Output
False True False True
False True False False

How it works:

  1. [] and {} are empty, so they are falsy.
  2. [0] holds one item and {"churned": 0} holds one key. Both are truthy. Truthiness looks at the container, not at the falsy item inside.
  3. "" is empty and falsy. " " holds a space and is truthy.
  4. None and 0.0 are falsy, as in module 01.

Alternative: test one value at a time in the REPL: >>> bool([0]).

M03-W03 · Plural labels with a conditional expression

Section titled “M03-W03 · Plural labels with a conditional expression”
Warm-up

Three customers from data/customers.csv have 0, 1 and 4 support tickets. Print one line per customer with the right word: ticket for exactly 1, tickets otherwise. Use a conditional expression.

Expected output
C00001: 0 tickets
C00003: 1 ticket
C00286: 4 tickets
Starter
customer_ids = ["C00001", "C00003", "C00286"]
tickets = [0, 1, 4]
for customer_id, count in zip(customer_ids, tickets, strict=True):
# TODO: choose "ticket" or "tickets" with a conditional expression
pass
Hint 1

The form is value_if_true if condition else value_if_false.

Hint 2

The condition is count == 1. Which word belongs on each side of it?

Solution
customer_ids = ["C00001", "C00003", "C00286"]
tickets = [0, 1, 4]
words = []
for customer_id, count in zip(customer_ids, tickets, strict=True):
word = "ticket" if count == 1 else "tickets"
words.append(word)
print(f"{customer_id}: {count} {word}")
assert words == ["tickets", "ticket", "tickets"]
Output
C00001: 0 tickets
C00003: 1 ticket
C00286: 4 tickets

How it works:

  1. zip() pairs each id with its ticket count.
  2. The conditional expression gives "ticket" only when the count is exactly 1. English uses the plural for 0 too.
  3. The f-string puts the count and the word into one line.

Alternative: put the expression inside the f-string: f"{count} ticket{'' if count == 1 else 's'}". It is shorter, but harder to read.

M03-W04 · A reading schedule with range()

Section titled “M03-W04 · A reading schedule with range()”
Warm-up

The sensors log a reading every 10 minutes. Print the six clock times of the first hour, from 00:00 to 00:50. Use range() with a step.

Expected output
00:00
00:10
00:20
00:30
00:40
00:50
Starter
# TODO: loop over the minutes 0, 10, ..., 50 with range()
# TODO: print each time as 00:MM
Hint 1

range(start, stop, step) excludes the stop value. Which stop gives 50 as the last number?

Hint 2

The stop must be a number above 50 and at most 60. The spec :02d pads 0 to 00.

Solution
times = []
for minute in range(0, 60, 10):
time_text = f"00:{minute:02d}"
times.append(time_text)
print(time_text)
assert len(times) == 6
assert times[-1] == "00:50"
Output
00:00
00:10
00:20
00:30
00:40
00:50

How it works:

  1. range(0, 60, 10) gives 0, 10, 20, 30, 40 and 50. The stop, 60, is excluded.
  2. :02d shows each number with at least 2 digits, so 0 becomes 00.
  3. times[-1] is the last item of the list.

Alternative: count the readings and multiply: for i in range(6): minute = i * 10. This form is useful when you also need the reading number i.

M03-W05 · Number the products with enumerate()

Section titled “M03-W05 · Number the products with enumerate()”
Warm-up

Print the five Electronics products of data/products.csv as a numbered list that starts at 1.

Expected output
1. Wireless Earbuds
2. Noise-Cancelling Headphones
3. 55-inch 4K Smart TV
4. 14-inch Ultrabook Laptop
5. Smartwatch Series 5
Starter
products = [
"Wireless Earbuds",
"Noise-Cancelling Headphones",
"55-inch 4K Smart TV",
"14-inch Ultrabook Laptop",
"Smartwatch Series 5",
]
# TODO: print "1. Wireless Earbuds" and so on with enumerate()
Hint 1

enumerate(products) gives pairs (position, item). Unpack them into two loop variables.

Hint 2

By default the positions start at 0. Pass start=1.

Solution
products = [
"Wireless Earbuds",
"Noise-Cancelling Headphones",
"55-inch 4K Smart TV",
"14-inch Ultrabook Laptop",
"Smartwatch Series 5",
]
last_number = 0
for number, product in enumerate(products, start=1):
print(f"{number}. {product}")
last_number = number
assert last_number == len(products)
Output
1. Wireless Earbuds
2. Noise-Cancelling Headphones
3. 55-inch 4K Smart TV
4. 14-inch Ultrabook Laptop
5. Smartwatch Series 5

How it works:

  1. enumerate(products, start=1) gives (1, "Wireless Earbuds"), (2, "Noise-Cancelling Headphones") and so on.
  2. for number, product in ... unpacks each pair.
  3. After the loop, the last number equals the number of products.

Alternative: for i in range(len(products)): print(f"{i + 1}. {products[i]}") gives the same lines. It needs an index and a + 1, which are two chances for a mistake.

M03-W06 · Pair stores and cities with zip()

Section titled “M03-W06 · Pair stores and cities with zip()”
Warm-up

Two parallel lists hold the first four store ids and their cities from data/stores.csv. Print one line per store.

Expected output
S01 Chicago
S02 Minneapolis
S03 Detroit
S04 Houston
Starter
store_ids = ["S01", "S02", "S03", "S04"]
cities = ["Chicago", "Minneapolis", "Detroit", "Houston"]
# TODO: loop over both lists together and print "S01 Chicago" and so on
Hint 1

zip(store_ids, cities) gives one pair per position.

Hint 2

Add strict=True, so a missing city raises an error instead of dropping a store.

Solution
store_ids = ["S01", "S02", "S03", "S04"]
cities = ["Chicago", "Minneapolis", "Detroit", "Houston"]
pairs = 0
for store_id, city in zip(store_ids, cities, strict=True):
print(store_id, city)
pairs += 1
assert pairs == 4
Output
S01 Chicago
S02 Minneapolis
S03 Detroit
S04 Houston

How it works:

  1. zip() takes the first item of each list, then the second, and so on.
  2. Each pair is unpacked into store_id and city.
  3. strict=True checks that both lists have the same length.

Alternative: a dict maps each id to its city: {"S01": "Chicago", ...}. Module 04 shows how to build it with dict(zip(store_ids, cities)).

M03-W07 · Fix the bug: a condition that is always true

Section titled “M03-W07 · Fix the bug: a condition that is always true”
Warm-up

Fix the bug: the code should count the order lines with a discount of 0.1 or 0.2. The discounts are the first eight lines of data/sales.csv. It prints 8, but only 2 lines have such a discount.

Starter
discounts = [0.05, 0.0, 0.0, 0.0, 0.1, 0.0, 0.1, 0.05]
big_discounts = 0
for discount in discounts:
if discount == 0.1 or 0.2: # TODO: fix this condition
big_discounts += 1
print("Lines with 10% or 20% off:", big_discounts)
Expected output
Lines with 10% or 20% off: 2
Hint 1

Python reads the condition as (discount == 0.1) or 0.2. What is the truthiness of 0.2?

Hint 2

Write both comparisons in full, or test membership with in.

Solution
discounts = [0.05, 0.0, 0.0, 0.0, 0.1, 0.0, 0.1, 0.05]
big_discounts = 0
for discount in discounts:
if discount == 0.1 or discount == 0.2:
big_discounts += 1
print("Lines with 10% or 20% off:", big_discounts)
assert big_discounts == 2
Output
Lines with 10% or 20% off: 2

How it works:

  1. In the bug, discount == 0.1 or 0.2 is 0.2 whenever the comparison is false. 0.2 is truthy, so the if block runs for every line.
  2. With both comparisons written in full, only the two lines with 0.1 count. No line in this sample has 0.2.
  3. Exact == on these floats is safe here, because the values are typed literals, not results of arithmetic.

Alternative: if discount in (0.1, 0.2): tests membership in a tuple. It is shorter and cannot repeat the bug.

M03-W08 · Describe a status code with match

Section titled “M03-W08 · Describe a status code with match”
Warm-up

The API module of this course uses four status codes. Print a short description for each code in the list. Any other code is other.

Expected output
200 ok
404 not found
429 rate limited
500 server error
302 other
Starter
codes = [200, 404, 429, 500, 302]
for code in codes:
# TODO: use match-case with literal patterns, an or-pattern and _
pass
Hint 1

case 200: matches the literal 200. case 500 | 502 | 503: matches any of three codes.

Hint 2

case _: catches everything else. Put it last.

Solution
codes = [200, 404, 429, 500, 302]
descriptions = []
for code in codes:
match code:
case 200:
text = "ok"
case 404:
text = "not found"
case 429:
text = "rate limited"
case 500 | 502 | 503:
text = "server error"
case _:
text = "other"
descriptions.append(text)
print(code, text)
assert descriptions[-1] == "other"
Output
200 ok
404 not found
429 rate limited
500 server error
302 other

How it works:

  1. Each literal pattern compares the subject code with ==.
  2. The or-pattern 500 | 502 | 503 groups three server errors into one case.
  3. 302 matches no literal, so the wildcard _ case runs.

Alternative: an if-elif chain works too. With only literal comparisons, both are fine. match wins once the subject has structure, as in M03-C07.

M03-W09 · Predict the output: break and continue

Section titled “M03-W09 · Predict the output: break and continue”
Warm-up

Predict the output: the loop walks through some raw lines of a sensor log.

Acceptance criteria:

  • Write the lines you expect, in order, then run the code.
  • Your prediction matches the Output in the solution.
Starter
lines = ["21.0", "", "21.9", "n/a", "STOP", "21.4"]
for line in lines:
if not line:
continue
if line == "STOP":
break
print("line:", line)
print("done")
# TODO: write your prediction before you run the code
Hint 1

continue skips the rest of one iteration. break leaves the loop.

Hint 2

"n/a" is not empty and is not "STOP".

Solution
lines = ["21.0", "", "21.9", "n/a", "STOP", "21.4"]
printed = 0
for line in lines:
if not line:
continue
if line == "STOP":
break
print("line:", line)
printed += 1
print("done")
assert printed == 3
Output
line: 21.0
line: 21.9
line: n/a
done

How it works:

  1. "21.0" is printed.
  2. "" is falsy, so continue skips it.
  3. "21.9" and "n/a" are printed. This loop does not validate numbers.
  4. "STOP" triggers break, so "21.4" is never reached. done runs after the loop.

Alternative: none needed; the point is to trace the flow by hand.

Core

Read data/readings.txt. Skip the empty and non-numeric lines. Find the highest valid reading and the line number where it first appears. Do not use max(): track the maximum in the loop.

Expected output
Hottest: 22.9 °C on line 8
Starter
from pathlib import Path
lines = Path("data/readings.txt").read_text(encoding="utf-8").splitlines()
highest = None
highest_line = None
# TODO: loop with enumerate(lines, start=1)
# TODO: skip invalid lines with continue
# TODO: update highest and highest_line when a reading is higher
Hint 1

A line is valid when line.strip() is not empty and text.replace(".", "", 1).isdigit() is true.

Hint 2

highest starts as None. Update it when highest is None or value > highest.

Hint 3

Use >, not >=, so a later equal value does not replace the first one.

Solution
from pathlib import Path
lines = Path("data/readings.txt").read_text(encoding="utf-8").splitlines()
highest = None
highest_line = None
for line_number, line in enumerate(lines, start=1):
text = line.strip()
if not text or not text.replace(".", "", 1).isdigit():
continue
value = float(text)
if highest is None or value > highest:
highest = value
highest_line = line_number
print(f"Hottest: {highest} °C on line {highest_line}")
assert highest == 22.9
assert highest_line == 8
Output
Hottest: 22.9 °C on line 8

How it works:

  1. enumerate(..., start=1) gives editor line numbers.
  2. The continue exit skips the 3 broken lines before float() sees them.
  3. highest is None handles the first valid reading, because nothing can be compared with None. Short-circuit evaluation then skips value > highest.
  4. 22.9 appears on lines 8 and 10. > keeps the first one.

Alternative: start with highest = float("-inf"), a float smaller than every number. Then if value > highest: is enough. The None version is clearer when the file could have no valid line at all.

M03-C02 · Segment customers by churn risk

Section titled “M03-C02 · Segment customers by churn risk”
Core

The retention team uses three segments. high: month-to-month contract and (tenure of 6 months or less or 3 or more support tickets). medium: not high, but 3 or fewer logins in 30 days or 3 or more tickets. low: everyone else. Label the five real customers below and count each segment.

Expected output
C02677 high
C03943 high
C04339 low
C00286 medium
C04557 low
{'high': 2, 'medium': 1, 'low': 2}
Starter
customers = [
{"customer_id": "C02677", "contract": "month-to-month", "tenure_months": 15,
"support_tickets": 3, "logins_last_30d": 16},
{"customer_id": "C03943", "contract": "month-to-month", "tenure_months": 6,
"support_tickets": 0, "logins_last_30d": 3},
{"customer_id": "C04339", "contract": "one-year", "tenure_months": 4,
"support_tickets": 0, "logins_last_30d": 13},
{"customer_id": "C00286", "contract": "two-year", "tenure_months": 66,
"support_tickets": 4, "logins_last_30d": 15},
{"customer_id": "C04557", "contract": "one-year", "tenure_months": 2,
"support_tickets": 1, "logins_last_30d": 37},
]
counts = {"high": 0, "medium": 0, "low": 0}
# TODO: label each customer with if/elif/else and print the label
# TODO: count the labels in counts and print counts
Hint 1

Put the high test first. It needs parentheses: contract == "month-to-month" and (tenure <= 6 or tickets >= 3).

Hint 2

Store each field in a short variable first. The conditions are then easier to read.

Solution
customers = [
{"customer_id": "C02677", "contract": "month-to-month", "tenure_months": 15,
"support_tickets": 3, "logins_last_30d": 16},
{"customer_id": "C03943", "contract": "month-to-month", "tenure_months": 6,
"support_tickets": 0, "logins_last_30d": 3},
{"customer_id": "C04339", "contract": "one-year", "tenure_months": 4,
"support_tickets": 0, "logins_last_30d": 13},
{"customer_id": "C00286", "contract": "two-year", "tenure_months": 66,
"support_tickets": 4, "logins_last_30d": 15},
{"customer_id": "C04557", "contract": "one-year", "tenure_months": 2,
"support_tickets": 1, "logins_last_30d": 37},
]
counts = {"high": 0, "medium": 0, "low": 0}
for customer in customers:
monthly = customer["contract"] == "month-to-month"
tenure = customer["tenure_months"]
tickets = customer["support_tickets"]
logins = customer["logins_last_30d"]
if monthly and (tenure <= 6 or tickets >= 3):
segment = "high"
elif logins <= 3 or tickets >= 3:
segment = "medium"
else:
segment = "low"
counts[segment] += 1
print(customer["customer_id"], segment)
print(counts)
assert counts == {"high": 2, "medium": 1, "low": 2}
Output
C02677 high
C03943 high
C04339 low
C00286 medium
C04557 low
{'high': 2, 'medium': 1, 'low': 2}

How it works:

  1. C02677 is month-to-month with 3 tickets, and C03943 is month-to-month with 6 months of tenure. Both are high.
  2. C00286 has 4 tickets but a two-year contract, so it is not high. The elif catches it as medium.
  3. C04339 has short tenure, but on a one-year contract with many logins it is low. C04557 is low too.
  4. Without the parentheses, and binds tighter than or, and every customer with 3 or more tickets would be high, whatever the contract.

Alternative: store the two sub-rules in named booleans, such as new_or_unhappy = tenure <= 6 or tickets >= 3. Then the if reads if monthly and new_or_unhappy:.

M03-C03 · Fix the bug: a real zero shown as unknown

Section titled “M03-C03 · Fix the bug: a real zero shown as unknown”
Core

Fix the bug: this report should show “unknown” only for a missing value (None). Customer C00077 really had 0 logins in the last 30 days, but the report says “unknown”. The last record is a made-up export row without a login count, so it has no customer id.

Starter
records = [
{"customer_id": "C00077", "logins_last_30d": 0},
{"customer_id": "C00001", "logins_last_30d": 17},
{"customer_id": "(no id)", "logins_last_30d": None},
]
for record in records:
logins = record["logins_last_30d"] or "unknown" # TODO: fix this line
print(record["customer_id"], logins)
Expected output
C00077 0
C00001 17
(no id) unknown
Hint 1

x or default returns the default whenever x is falsy. Which falsy values can a login count have?

Hint 2

Use a conditional expression with is None.

Solution
records = [
{"customer_id": "C00077", "logins_last_30d": 0},
{"customer_id": "C00001", "logins_last_30d": 17},
{"customer_id": "(no id)", "logins_last_30d": None},
]
shown = []
for record in records:
raw = record["logins_last_30d"]
logins = "unknown" if raw is None else raw
shown.append(logins)
print(record["customer_id"], logins)
assert shown == [0, 17, "unknown"]
Output
C00077 0
C00001 17
(no id) unknown

How it works:

  1. 0 or "unknown" gives "unknown", because 0 is falsy. That is the bug.
  2. "unknown" if raw is None else raw replaces only None. A real 0 stays 0.
  3. This matters for churn models. Low activity is a strong churn signal: customers with 3 or fewer logins churn at 42.5%, against 19.3% overall. A real 0 must not disappear into “unknown”.

Alternative: a full if raw is None: block. Use it when the missing case needs more than one statement, such as logging the record.

Core

Fix the bug: the three lines of orders O000004 and O000006 from data/sales.csv should total 2,467.19 USD. The code prints a smaller total. Find the cause, make the code fail loudly on such data, and then fix the data. The missing quantity of the laptop line is 2.

Starter
unit_prices = [59.99, 249.00, 1149.00]
quantities = [1, 1] # TODO: one value is missing
discounts = [0.0, 0.1, 0.05]
total = 0.0
for price, quantity, discount in zip(unit_prices, quantities, discounts):
total += round(price * quantity * (1 - discount), 2)
print(f"Total: {total:.2f} USD")

Acceptance criteria:

  • With strict=True and the broken data, the loop raises ValueError: zip() argument 2 is shorter than argument 1.
  • After you add the missing quantity, the script prints Total: 2467.19 USD.
Hint 1

zip() stops at the shortest input. How long is quantities?

Hint 2

Add strict=True first and run the code: it now raises a ValueError. Then add the missing quantity.

Solution

The bug, made visible with strict=True:

unit_prices = [59.99, 249.00, 1149.00]
quantities = [1, 1]
discounts = [0.0, 0.1, 0.05]
for price, quantity, discount in zip(unit_prices, quantities, discounts, strict=True):
print(price, quantity, discount)
Output
59.99 1 0.0
249.0 1 0.1
ValueError: zip() argument 2 is shorter than argument 1

The fix:

import math
unit_prices = [59.99, 249.00, 1149.00]
quantities = [1, 1, 2]
discounts = [0.0, 0.1, 0.05]
total = 0.0
for price, quantity, discount in zip(unit_prices, quantities, discounts, strict=True):
total += round(price * quantity * (1 - discount), 2)
print(f"Total: {total:.2f} USD")
assert math.isclose(total, 59.99 + 224.1 + 2183.1)
Output
Total: 2467.19 USD

How it works:

  1. Without strict=True, zip() gives only two triples and silently drops the laptop line, the most expensive one.
  2. With strict=True, the same data raises ValueError: zip() argument 2 is shorter than argument 1. The error names the short list.
  3. With the missing quantity added, the total includes all three lines. The assert compares it with the sum of the three revenues in the file.

Alternative: store each line as one record, such as a dict with price, quantity and discount. A record cannot lose one field without the others. Module 04 shows lists of dicts and tuples.

Core

Total revenue in data/sales.csv was 1,950,934.24 USD in 2024, up 18.6% from 2023. Assume it keeps growing by 18.6% per year. Use a while loop to find the first year in which revenue is at least twice the 2024 value. Print each year on the way.

Expected output
2025: 2,313,808 USD
2026: 2,744,176 USD
2027: 3,254,593 USD
2028: 3,859,947 USD
2029: 4,577,898 USD
Doubled in 2029
Starter
revenue = 1_950_934.24
target = 2 * revenue
year = 2024
# TODO: while revenue is below the target, grow it by 18.6% and add 1 to year
# TODO: print each year and its revenue with :,.0f
Hint 1

Growing by 18.6% means multiplying by 1.186.

Hint 2

The loop condition is revenue < target. Update year and revenue inside the loop, then print.

Solution
revenue = 1_950_934.24
target = 2 * revenue
year = 2024
while revenue < target:
revenue *= 1.186
year += 1
print(f"{year}: {revenue:,.0f} USD")
print("Doubled in", year)
assert year == 2029
assert revenue >= target
Output
2025: 2,313,808 USD
2026: 2,744,176 USD
2027: 3,254,593 USD
2028: 3,859,947 USD
2029: 4,577,898 USD
Doubled in 2029

How it works:

  1. The loop runs while revenue is below the target. You do not know the number of years in advance, which is why while fits.
  2. Each iteration multiplies by 1.186 and counts one year.
  3. After 4 years, revenue is 1.98 times the start, still short. The fifth year passes the target.

Alternative: solve it with logarithms: math.ceil(math.log(2) / math.log(1.186)) gives 5 years. The loop is easier to adapt, for example to a growth rate that changes each year.

Core

data/config.json sets a retry policy: 3 attempts, waiting 1, 2 and then 4 seconds. This is backoff: a wait between retries that grows after each failure, so a struggling server gets more time to recover. Simulate the policy on a list of status codes that the server returns, one per attempt. Stop at the first 200. If all attempts fail, print giving up. Use a while loop with an else block. Do not really wait.

Expected output
attempt 1: 503, wait 1 s
attempt 2: 503, wait 2 s
attempt 3: 200 ok
---
attempt 1: 503, wait 1 s
attempt 2: 500, wait 2 s
attempt 3: 503, wait 4 s
giving up
---
Starter
backoff_seconds = [1, 2, 4]
max_attempts = 3
for statuses in ([503, 503, 200], [503, 500, 503]):
attempt = 0
# TODO: while attempt < max_attempts: read the status of this attempt
# TODO: on 200 print "attempt N: 200 ok" and break
# TODO: else print "attempt N: STATUS, wait S s" and continue
# TODO: else block of the while: print "giving up"
print("---")
Hint 1

The status of attempt attempt (counting from 0) is statuses[attempt], and its wait is backoff_seconds[attempt].

Hint 2

Increase attempt in every iteration, or the loop never ends. The else of the while runs only when no break happened.

Solution
backoff_seconds = [1, 2, 4]
max_attempts = 3
results = []
for statuses in ([503, 503, 200], [503, 500, 503]):
attempt = 0
while attempt < max_attempts:
status = statuses[attempt]
if status == 200:
print(f"attempt {attempt + 1}: 200 ok")
results.append("ok")
break
print(f"attempt {attempt + 1}: {status}, wait {backoff_seconds[attempt]} s")
attempt += 1
else: # no break: every attempt failed
print("giving up")
results.append("failed")
print("---")
assert results == ["ok", "failed"]
Output
attempt 1: 503, wait 1 s
attempt 2: 503, wait 2 s
attempt 3: 200 ok
---
attempt 1: 503, wait 1 s
attempt 2: 500, wait 2 s
attempt 3: 503, wait 4 s
giving up
---

How it works:

  1. The outer for runs two scenarios. The inner while is the retry loop.
  2. On a 200, break leaves the while, and the else block is skipped.
  3. When all 3 attempts fail, the condition attempt < max_attempts becomes false. The loop ends normally, so the else block prints giving up.
  4. A real script would call time.sleep(backoff_seconds[attempt]) before the next attempt (module 09) and send a real request (module 16).

Alternative: for attempt in range(max_attempts): with the same break and else. Because the number of attempts is fixed, a for loop is a natural fit too, and it cannot forget to increase the counter.

M03-C07 · Route order events with mapping patterns

Section titled “M03-C07 · Route order events with mapping patterns”
Core

An order service emits events as dicts. Use match with mapping patterns to process them: add the amount of an order, subtract the amount of a refund, count a signup, and collect every other event as a problem. Print the net revenue, the signups and the problems. The orders and the refund are real lines from data/sales.csv; the signup is customer C04991.

Expected output
welcome C04991
Net revenue: 2243.09 USD
Signups: 1
Problems: [{'type': 'order', 'order_id': 'O000007'}, {'type': 'ping'}]
Starter
events = [
{"type": "order", "order_id": "O000004", "amount": 284.09},
{"type": "order", "order_id": "O000006", "amount": 2183.1},
{"type": "refund", "order_id": "O000004", "amount": 224.1},
{"type": "signup", "customer_id": "C04991", "plan": "standard"},
{"type": "order", "order_id": "O000007"},
{"type": "ping"},
]
net_revenue = 0.0
signups = 0
problems = []
# TODO: match each event and update the three accumulators
Hint 1

case {"type": "order", "amount": amount}: matches an order with an amount and captures it.

Hint 2

The order without "amount" does not match the order case. Let it fall to case _: and append the event to problems.

Solution
import math
events = [
{"type": "order", "order_id": "O000004", "amount": 284.09},
{"type": "order", "order_id": "O000006", "amount": 2183.1},
{"type": "refund", "order_id": "O000004", "amount": 224.1},
{"type": "signup", "customer_id": "C04991", "plan": "standard"},
{"type": "order", "order_id": "O000007"},
{"type": "ping"},
]
net_revenue = 0.0
signups = 0
problems = []
for event in events:
match event:
case {"type": "order", "amount": float(amount) | int(amount)}:
net_revenue += amount
case {"type": "refund", "amount": float(amount) | int(amount)}:
net_revenue -= amount
case {"type": "signup", "customer_id": customer_id}:
signups += 1
print("welcome", customer_id)
case _:
problems.append(event)
print(f"Net revenue: {net_revenue:.2f} USD")
print("Signups:", signups)
print("Problems:", problems)
assert math.isclose(net_revenue, 284.09 + 2183.1 - 224.1)
assert len(problems) == 2
Output
welcome C04991
Net revenue: 2243.09 USD
Signups: 1
Problems: [{'type': 'order', 'order_id': 'O000007'}, {'type': 'ping'}]

How it works:

  1. Each mapping pattern checks the "type" and the keys that the case needs, then captures the values.
  2. float(amount) | int(amount) combines two class patterns: it accepts a whole-number amount such as 100 as well as 284.09, and rejects an amount sent as text, such as "284.09". With float(amount) alone, a valid amount of 100 would end up in problems, because 100 is an int, not a float.
  3. The order O000007 has no "amount", so no order case matches. It ends in problems with the unknown "ping" event.
  4. Order O000004 had two lines (Slim Fit Jeans 59.99 and the headphones 224.10). The refund removes the headphones.

Alternative: an if-elif chain on event["type"], with "amount" in event checks. It needs more code and fails with a KeyError when you forget one check.

M03-C08 · Parse command-line words with sequence patterns

Section titled “M03-C08 · Parse command-line words with sequence patterns”
Core

A small report tool receives its arguments as a list of words, like sys.argv[1:] (the command-line words after the script name) in module 08. Parse each command with sequence patterns: report STORE, report STORE --month MONTH, stores and help. Anything else is a usage error. Print what the tool would do.

Expected output
full report for S01
report for S07 in 2024-05
list the 12 stores
show help
usage error: report
show help
Starter
commands = [
["report", "S01"],
["report", "S07", "--month", "2024-05"],
["stores"],
["help"],
["report"],
[],
]
for words in commands:
# TODO: match words against sequence patterns
pass
Hint 1

case ["report", store_id]: matches exactly two words and captures the second.

Hint 2

case ["help"] | []: treats an empty command like help. Put case _: last for usage errors.

Solution
commands = [
["report", "S01"],
["report", "S07", "--month", "2024-05"],
["stores"],
["help"],
["report"],
[],
]
actions = []
for words in commands:
match words:
case ["report", store_id]:
action = f"full report for {store_id}"
case ["report", store_id, "--month", month]:
action = f"report for {store_id} in {month}"
case ["stores"]:
action = "list the 12 stores"
case ["help"] | []:
action = "show help"
case _:
action = f"usage error: {' '.join(words)}"
actions.append(action)
print(action)
assert actions[4] == "usage error: report"
Output
full report for S01
report for S07 in 2024-05
list the 12 stores
show help
usage error: report
show help

How it works:

  1. Each sequence pattern fixes the number of words and the literal words, and captures the rest.
  2. ["report"] alone has one word, so neither report pattern matches. It falls to case _.
  3. The empty list matches [] in the or-pattern and shows the help, as many tools do.
  4. ' '.join(words) joins the words with spaces (module 02).

Alternative: module 08 shows argparse, the standard library tool for real command-line parsing. It writes help and error messages for you. match is a good fit for small internal tools and for chat or bot commands.

M03-C09 · Search for an out-of-stock product with loop else

Section titled “M03-C09 · Search for an out-of-stock product with loop else”
Core

The first page of data/api/products_page_1.json lists product ids, categories and stock levels. For each category in ["Home", "Electronics"], find the first product of that category with stock 0, or print that the category is fully in stock. Use a for loop with break and else.

Expected output
Home: P006 is out of stock
Electronics: fully in stock
Starter
items = [
("P001", "Electronics", 92), ("P002", "Electronics", 151),
("P003", "Electronics", 16), ("P004", "Electronics", 37),
("P005", "Electronics", 85), ("P006", "Home", 0),
("P007", "Home", 84), ("P008", "Home", 183),
("P009", "Home", 140), ("P010", "Home", 64),
]
for category in ["Home", "Electronics"]:
# TODO: search items for the first product of this category with stock 0
# TODO: use break when found and else for "fully in stock"
pass
Hint 1

The inner loop is for product_id, item_category, stock in items:. Both conditions must be true.

Hint 2

The else lines up with the inner for, not with the if.

Solution
items = [
("P001", "Electronics", 92), ("P002", "Electronics", 151),
("P003", "Electronics", 16), ("P004", "Electronics", 37),
("P005", "Electronics", 85), ("P006", "Home", 0),
("P007", "Home", 84), ("P008", "Home", 183),
("P009", "Home", 140), ("P010", "Home", 64),
]
found = []
for category in ["Home", "Electronics"]:
for product_id, item_category, stock in items:
if item_category == category and stock == 0:
print(f"{category}: {product_id} is out of stock")
found.append(product_id)
break
else: # no break: nothing found in this category
print(f"{category}: fully in stock")
assert found == ["P006"]
Output
Home: P006 is out of stock
Electronics: fully in stock

How it works:

  1. The outer loop picks a category. The inner loop searches the items.
  2. For Home, P006 has stock 0. break ends the inner loop only, and the outer loop moves on.
  3. For Electronics, no item matches. The inner loop ends normally, so its else block runs.

Alternative: read the real file with json (module 07): json.loads(Path("data/api/products_page_1.json").read_text())["data"] gives the list of item dicts, and the loop reads item["stock"].

Core

Refactor: this code works, but it uses range(len(...)) and indexes three lists. Rewrite it with enumerate() and zip() and no indexing. The output must stay the same. The data are the first three S1 readings of data/sensors.csv.

Starter
times = ["00:00", "00:10", "00:20"]
temperatures = [20.21, 20.22, 20.16]
humidities = [57.1, 56.5, 57.1]
for i in range(len(times)):
print(f"{i + 1}. {times[i]} {temperatures[i]:.2f} °C {humidities[i]:.1f} %")
# TODO: rewrite the loop with enumerate() and zip()
Expected output
1. 00:00 20.21 °C 57.1 %
2. 00:10 20.22 °C 56.5 %
3. 00:20 20.16 °C 57.1 %
Hint 1

zip(times, temperatures, humidities, strict=True) gives one triple per reading.

Hint 2

Wrap the zip() in enumerate(..., start=1). Each item is then (number, (time, temperature, humidity)).

Solution
times = ["00:00", "00:10", "00:20"]
temperatures = [20.21, 20.22, 20.16]
humidities = [57.1, 56.5, 57.1]
rows = zip(times, temperatures, humidities, strict=True)
count = 0
for number, (time, temperature, humidity) in enumerate(rows, start=1):
print(f"{number}. {time} {temperature:.2f} °C {humidity:.1f} %")
count = number
assert count == 3
Output
1. 00:00 20.21 °C 57.1 %
2. 00:10 20.22 °C 56.5 %
3. 00:20 20.16 °C 57.1 %

How it works:

  1. zip() builds the triples. strict=True adds a length check that the index version did not have.
  2. enumerate(rows, start=1) adds the number and removes the i + 1.
  3. The parentheses in (time, temperature, humidity) unpack the inner triple in the same line.
  4. The behavior is unchanged, so this is a true refactor.

Alternative: keep the number out if you do not need it: for time, temperature, humidity in zip(...). Add enumerate() only when the position is part of the output.

Core

Choose a method and justify it: solve each task with the loop that fits best, for, while or for-else. Use the first 10 lines of data/readings.txt.

  1. The mean of the 10 readings.
  2. The P001 Wireless Earbuds have 92 units in stock and sell about 7 per day. After how many full days is the stock below 20 units, the reorder point?
  3. The first reading above 22.6 °C, or a “none” message.
Expected output
1. Mean: 22.06 °C
2. Below the reorder point after 11 days (15 units left)
3. First reading above 22.6: 22.9 (line 8)
Starter
readings = [21.0, 21.9, 21.4, 21.7, 22.1, 22.0, 22.5, 22.9, 22.2, 22.9]
stock = 92
# TODO: task 1
# TODO: task 2
# TODO: task 3
Hint 1

Task 1 visits every item once. Task 2 repeats an unknown number of times. Task 3 is a search that may find nothing.

Hint 2

Task 3 uses break inside the loop and else after it.

Solution
readings = [21.0, 21.9, 21.4, 21.7, 22.1, 22.0, 22.5, 22.9, 22.2, 22.9]
stock = 92
# 1. Every item once: a for loop (or simply sum()).
total = 0.0
for reading in readings:
total += reading
mean = total / len(readings)
print(f"1. Mean: {mean:.2f} °C")
# 2. Unknown number of repetitions: a while loop.
days = 0
while stock >= 20:
stock -= 7
days += 1
print(f"2. Below the reorder point after {days} days ({stock} units left)")
# 3. A search that may fail: for-else.
for position, reading in enumerate(readings, start=1):
if reading > 22.6:
print(f"3. First reading above 22.6: {reading} (line {position})")
break
else:
print("3. No reading above 22.6")
assert days == 11 and stock == 15
Output
1. Mean: 22.06 °C
2. Below the reorder point after 11 days (15 units left)
3. First reading above 22.6: 22.9 (line 8)

How it works:

  1. Mean: the loop visits each reading once, so for fits. In real code, sum(readings) / len(readings) is shorter.
  2. Stock: you do not know in advance how many days it takes, so the stop condition drives the loop. After 10 days 22 units remain, which is still at or above 20. After 11 days 15 units remain.
  3. Search: for-else stops at the first match and has a clear place for “not found”. Line 8 holds 22.9.

Alternative: task 2 has a formula too: (92 - 20) // 7 + 1 days. The loop version is easier to change when sales differ per day.

M03-C12 · Tune and interpret a classification threshold

Section titled “M03-C12 · Tune and interpret a classification threshold”
Core

A churn model gives each of 8 test customers a probability of churning. A customer is flagged when the probability is at or above a threshold. For each threshold in [0.3, 0.5, 0.7], count the true positives (flagged and really churned) and the false positives (flagged but did not churn). Module 36 covers these metrics in depth.

Then interpret the result: a retention call costs USD 5 and a lost customer costs USD 300. Assume that a call keeps the customer. The cost of a threshold is USD 5 per flagged customer plus USD 300 per churner who was not flagged. Print the counts (TP for true positives, FP for false positives), the cost of each threshold and the cheapest one, and explain in one or two sentences why it wins.

Expected output
threshold 0.3: 4 TP, 2 FP, cost USD 30
threshold 0.5: 3 TP, 1 FP, cost USD 320
threshold 0.7: 2 TP, 0 FP, cost USD 610
Cheapest: threshold 0.3 (USD 30)
Starter
probabilities = [0.92, 0.81, 0.64, 0.55, 0.47, 0.33, 0.21, 0.08]
churned = [1, 1, 0, 1, 0, 1, 0, 0]
for threshold in [0.3, 0.5, 0.7]:
true_pos = 0
false_pos = 0
# TODO: loop over both lists together and count
# TODO: compute the cost and print one line per threshold
# TODO: print the cheapest threshold
Hint 1

This is a nested loop: the outer loop picks a threshold, the inner loop walks the customers with zip().

Hint 2

Skip customers below the threshold with continue. For the others, churned == 1 decides between a true and a false positive.

Hint 3

The number of churners is sum(churned). The missed churners are sum(churned) - true_pos. Track the cheapest threshold with the maximum pattern, turned around for a minimum.

Solution
probabilities = [0.92, 0.81, 0.64, 0.55, 0.47, 0.33, 0.21, 0.08]
churned = [1, 1, 0, 1, 0, 1, 0, 0]
call_cost, lost_cost = 5, 300
results = []
best_threshold, best_cost = None, None
for threshold in [0.3, 0.5, 0.7]:
true_pos = 0
false_pos = 0
for probability, label in zip(probabilities, churned, strict=True):
if probability < threshold:
continue
if label == 1:
true_pos += 1
else:
false_pos += 1
missed = sum(churned) - true_pos
cost = call_cost * (true_pos + false_pos) + lost_cost * missed
results.append((true_pos, false_pos))
print(f"threshold {threshold}: {true_pos} TP, {false_pos} FP, cost USD {cost}")
if best_cost is None or cost < best_cost:
best_threshold, best_cost = threshold, cost
print(f"Cheapest: threshold {best_threshold} (USD {best_cost})")
assert results == [(4, 2), (3, 1), (2, 0)]
assert best_threshold == 0.3
Output
threshold 0.3: 4 TP, 2 FP, cost USD 30
threshold 0.5: 3 TP, 1 FP, cost USD 320
threshold 0.7: 2 TP, 0 FP, cost USD 610
Cheapest: threshold 0.3 (USD 30)

How it works:

  1. The counters are reset at the start of each outer iteration. Otherwise, each threshold would add to the previous counts.
  2. continue skips the customers who are not flagged.
  3. missed is the number of churners below the threshold. The cost adds USD 5 per call and USD 300 per missed churner.
  4. Interpretation: 0.3 wins at USD 30. It calls 2 loyal customers for nothing (USD 10 wasted), but it misses no churner. Each missed churner costs as much as 60 calls, so when a miss is this expensive, a low threshold that flags generously is the right choice. With cheaper customers or expensive calls, the answer can flip. The threshold is a business decision, not a property of the model.

Alternative: count with a conditional sum, such as sum(1 for p, y in zip(...) if p >= threshold and y == 1). Module 04 introduces this generator expression form.

Challenge

In data/readings.txt, find the longest run of consecutive valid readings above 22.0 °C. A broken line (empty or not a number) ends a run. Print the length of the longest run and the line numbers where it starts and ends.

Expected output
Longest run above 22.0 °C: 5 readings
From line 7 to line 11
Starter
from pathlib import Path
lines = Path("data/readings.txt").read_text(encoding="utf-8").splitlines()
# TODO: track the current run (length and start line)
# TODO: track the best run (length, start line, end line)
# TODO: a broken line or a reading <= 22.0 resets the current run
Hint 1

Keep four variables: run_length, run_start, best_length and best_start. best_end follows from them.

Hint 2

When a reading is above 22.0: if run_length == 0, the run starts on this line. Add 1 to run_length. Then compare it with best_length.

Hint 3

When a line is broken or not above 22.0, set run_length = 0 and continue.

Solution
from pathlib import Path
lines = Path("data/readings.txt").read_text(encoding="utf-8").splitlines()
run_length = 0
run_start = 0
best_length = 0
best_start = 0
best_end = 0
for line_number, line in enumerate(lines, start=1):
text = line.strip()
valid = bool(text) and text.replace(".", "", 1).isdigit()
if not valid or float(text) <= 22.0:
run_length = 0
continue
if run_length == 0:
run_start = line_number
run_length += 1
if run_length > best_length:
best_length = run_length
best_start = run_start
best_end = line_number
if best_length:
print(f"Longest run above 22.0 °C: {best_length} readings")
print(f"From line {best_start} to line {best_end}")
else:
print("No reading above 22.0 °C")
assert best_end - best_start + 1 == best_length
assert (best_start, best_end) == (7, 11)
Output
Longest run above 22.0 °C: 5 readings
From line 7 to line 11

How it works:

  1. valid uses short-circuit evaluation: for an empty line, bool(text) is False, and .isdigit() is never called. In the if, not valid or ... protects float(text) the same way.
  2. Every line that is broken or not warm resets the current run and leaves the iteration with continue.
  3. A warm line after a reset starts a new run. Each warm line extends the run and, if it is the longest so far, updates the best run.
  4. Lines 7 to 11 (22.5, 22.9, 22.2, 22.9, 22.7) form the longest run. Line 12 is error, which ends it.
  5. The first assert is an invariant: a run from line a to line b has b − a + 1 readings.

Alternative: itertools.groupby() (module 09) groups consecutive items by a key, such as “warm or not”, and gives each run in one step.

M03-X02 · Process an event stream with match

Section titled “M03-X02 · Process an event stream with match”
Challenge

A shop sends events with nested data. Process them with one match statement per event:

  • order with a store_id and a non-empty lines list: add the line amounts to that store.
  • order with an empty lines list: a problem empty order O....
  • refund with a positive amount: subtract it from that store.
  • refund with an amount of 0 or less: a problem bad refund O....
  • anything else: a problem unknown event.

Print the net revenue per store, sorted by store id, and the problems. The first three orders and the first refund are real lines from data/sales.csv. The two broken test events use the made-up order ids O999998 and O999999.

Expected output
S07: 2183.10 USD
S09: 146.95 USD
S11: 59.99 USD
Problems: ['empty order O999998', 'bad refund O999999', 'unknown event']
Starter
events = [
{"type": "order", "order_id": "O000004", "store_id": "S11",
"lines": [59.99, 224.1]},
{"type": "order", "order_id": "O000005", "store_id": "S09",
"lines": [29.99, 116.96]},
{"type": "order", "order_id": "O000006", "store_id": "S07", "lines": [2183.1]},
{"type": "refund", "order_id": "O000004", "store_id": "S11", "amount": 224.1},
{"type": "order", "order_id": "O999998", "store_id": "S07", "lines": []},
{"type": "refund", "order_id": "O999999", "store_id": "S09", "amount": -5.0},
{"type": "shipment", "order_id": "O000006"},
]
net = {}
problems = []
# TODO: match each event
# TODO: print the stores in sorted order, then the problems
Hint 1

Order the cases so that the empty order comes before the general order: "lines": [] before "lines": [first, *rest].

Hint 2

Use a guard for the refund: case {"type": "refund", "store_id": store, "amount": float(amount)} if amount > 0:.

Hint 3

A store may not be in net yet. Use if store not in net: net[store] = 0.0 before you add. sorted(net) gives the keys in order.

Solution
import math
events = [
{"type": "order", "order_id": "O000004", "store_id": "S11",
"lines": [59.99, 224.1]},
{"type": "order", "order_id": "O000005", "store_id": "S09",
"lines": [29.99, 116.96]},
{"type": "order", "order_id": "O000006", "store_id": "S07", "lines": [2183.1]},
{"type": "refund", "order_id": "O000004", "store_id": "S11", "amount": 224.1},
{"type": "order", "order_id": "O999998", "store_id": "S07", "lines": []},
{"type": "refund", "order_id": "O999999", "store_id": "S09", "amount": -5.0},
{"type": "shipment", "order_id": "O000006"},
]
net = {}
problems = []
for event in events:
match event:
case {"type": "order", "order_id": order_id, "lines": []}:
problems.append(f"empty order {order_id}")
case {"type": "order", "store_id": store, "lines": [first, *rest]}:
if store not in net:
net[store] = 0.0
net[store] += first
for amount in rest:
net[store] += amount
case {"type": "refund", "store_id": store, "amount": float(amount)} if (
amount > 0
):
if store not in net:
net[store] = 0.0
net[store] -= amount
case {"type": "refund", "order_id": order_id}:
problems.append(f"bad refund {order_id}")
case _:
problems.append("unknown event")
for store in sorted(net):
print(f"{store}: {net[store]:.2f} USD")
print("Problems:", problems)
assert math.isclose(net["S11"], 59.99)
assert len(problems) == 3
Output
S07: 2183.10 USD
S09: 146.95 USD
S11: 59.99 USD
Problems: ['empty order O999998', 'bad refund O999999', 'unknown event']

How it works:

  1. "lines": [] matches only an empty list, so the empty test order O999998 becomes a problem before the general order case can see it.
  2. [first, *rest] matches a list with at least one amount. The loop adds first and then every item of rest.
  3. The guard if amount > 0 lets only positive refunds through. The refund of −5.0 falls to the next case, which reports it.
  4. The shipment event matches no order or refund pattern, so case _ reports it.
  5. sorted(net) returns the store ids in order, so the report does not depend on the order of the events.

Alternative: capture the whole list with "lines": [_, *_] as amounts and add with sum(amounts). Or check "lines": list(amounts) and test if amounts in the body.

Challenge

Fit price = w × size on the four houses of the lesson’s Example 7 with gradient descent. Try the learning rates [0.01, 0.1, 0.3, 0.6]. For each rate, run a while loop with at most 200 iterations. Stop when abs(step) < 1e-6 (converged) or when abs(w) > 1e6 (diverged). Print the result of each rate and the fastest converging rate.

Expected output
rate 0.01: not converged after 200 iterations, w = 3.037
rate 0.1: converged after 28 iterations, w = 3.037
rate 0.3: converged after 12 iterations, w = 3.037
rate 0.6: diverged after 32 iterations, w = -1.283e+06
Fastest: rate 0.3 (12 iterations)
Starter
sizes = [0.8, 1.2, 1.5, 2.0]
prices = [2.5, 3.5, 4.6, 6.1]
max_iter = 200
best_rate = None
best_iterations = None
for learning_rate in [0.01, 0.1, 0.3, 0.6]:
w = 0.0
iteration = 0
# TODO: while loop with a convergence break and a divergence break
# TODO: else block for "no convergence within max_iter"
# TODO: remember the rate with the fewest iterations among the converged ones
Hint 1

Inside the while, compute the gradient with an inner for loop over zip(sizes, prices), exactly as in the lesson.

Hint 2

Both stop cases use break, so you need a variable such as status to tell them apart after the loop.

Hint 3

Update the best rate only when status == "converged" and best_iterations is None or iteration < best_iterations.

Solution
sizes = [0.8, 1.2, 1.5, 2.0]
prices = [2.5, 3.5, 4.6, 6.1]
max_iter = 200
best_rate = None
best_iterations = None
for learning_rate in [0.01, 0.1, 0.3, 0.6]:
w = 0.0
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) < 1e-6:
status = "converged"
break
if abs(w) > 1e6:
status = "diverged"
break
else: # no break: the iteration limit was reached
status = "not converged"
print(f"rate {learning_rate}: {status} after {iteration} iterations, w = {w:.4g}")
faster = best_iterations is None or iteration < best_iterations
if status == "converged" and faster:
best_rate = learning_rate
best_iterations = iteration
print(f"Fastest: rate {best_rate} ({best_iterations} iterations)")
assert best_rate == 0.3
Output
rate 0.01: not converged after 200 iterations, w = 3.037
rate 0.1: converged after 28 iterations, w = 3.037
rate 0.3: converged after 12 iterations, w = 3.037
rate 0.6: diverged after 32 iterations, w = -1.283e+06
Fastest: rate 0.3 (12 iterations)

How it works:

  1. Three nested levels: the rates (for), the training (while) and the gradient sum (for).
  2. The two break statements leave the while early. The status variable records why. The loop else covers the third outcome: the limit was reached.
  3. A rate of 0.01 moves too slowly: after 200 iterations w is close, but each step is still larger than the tolerance. 0.6 overshoots and diverges. 0.1 and 0.3 converge, and 0.3 is faster.
  4. :.4g shows 4 significant digits, which suits both 3.037 and a diverged value such as -1.283e+06.

Alternative: this is a tiny version of a hyperparameter search. A hyperparameter is a setting that you choose before training, such as the learning rate, rather than a value the model learns, such as w. Module 37 does the same with GridSearchCV, and scikit-learn models stop with the same two ideas: a tolerance (tol) and an iteration limit (max_iter).

M03-X04 · A rate-limit-aware download loop

Section titled “M03-X04 · A rate-limit-aware download loop”
Challenge

A script downloads all pages of the product API. The (simulated) server answers with the responses below, in order, one per request. The item lists are shortened to a few product ids. Write a loop that sends requests until the last page arrives, using match on each response:

  • 200 with a next URL: count the items and continue.
  • 200 with next set to None: count the items and stop with done.
  • 429 with retry_after: add the wait to a total wait time and retry.
  • 5xx: retry, but stop with failed after 2 server errors in a row.

Stop with failed too if more than 10 requests are needed. Print each step and a summary. Do not really wait.

Expected output
page 1: 3 items
rate limited: wait 30 s
server error 503 (1 in a row)
page 2: 2 items
server error 503 (1 in a row)
page 3: 2 items, last page
done: 7 items, 6 requests, 30 s waited
Starter
responses = [
{"status": 200, "page": 1, "data": ["P001", "P002", "P003"], "next": "page=2"},
{"status": 429, "retry_after": 30},
{"status": 503},
{"status": 200, "page": 2, "data": ["P011", "P012"], "next": "page=3"},
{"status": 503},
{"status": 200, "page": 3, "data": ["P021", "P022"], "next": None},
]
requests_sent = 0
items = 0
waited = 0
server_errors_in_a_row = 0
outcome = None
# TODO: while outcome is None: take the next response and match it
Hint 1

The response of request number requests_sent is responses[requests_sent]. Increase requests_sent right after you take it.

Hint 2

Put case {"status": 200, "data": data, "next": None}: before the general 200 case. A guard such as if code >= 500 catches the server errors.

Hint 3

Reset server_errors_in_a_row to 0 after every successful response.

Solution
responses = [
{"status": 200, "page": 1, "data": ["P001", "P002", "P003"], "next": "page=2"},
{"status": 429, "retry_after": 30},
{"status": 503},
{"status": 200, "page": 2, "data": ["P011", "P012"], "next": "page=3"},
{"status": 503},
{"status": 200, "page": 3, "data": ["P021", "P022"], "next": None},
]
max_requests = 10
requests_sent = 0
items = 0
waited = 0
server_errors_in_a_row = 0
outcome = None
while outcome is None:
if requests_sent >= max_requests or requests_sent >= len(responses):
outcome = "failed"
break
response = responses[requests_sent]
requests_sent += 1
match response:
case {"status": 200, "page": page, "data": data, "next": None}:
items += len(data)
server_errors_in_a_row = 0
print(f"page {page}: {len(data)} items, last page")
outcome = "done"
case {"status": 200, "page": page, "data": data}:
items += len(data)
server_errors_in_a_row = 0
print(f"page {page}: {len(data)} items")
case {"status": 429, "retry_after": int(seconds)}:
waited += seconds
print(f"rate limited: wait {seconds} s")
case {"status": int(code)} if code >= 500:
server_errors_in_a_row += 1
print(f"server error {code} ({server_errors_in_a_row} in a row)")
if server_errors_in_a_row >= 2:
outcome = "failed"
case _:
print("unexpected response:", response)
outcome = "failed"
print(f"{outcome}: {items} items, {requests_sent} requests, {waited} s waited")
assert outcome == "done"
assert items == 7
Output
page 1: 3 items
rate limited: wait 30 s
server error 503 (1 in a row)
page 2: 2 items
server error 503 (1 in a row)
page 3: 2 items, last page
done: 7 items, 6 requests, 30 s waited

How it works:

  1. The while condition outcome is None keeps the loop going until a case sets an outcome.
  2. The guard at the top is the safety limit: it ends the loop after max_requests requests, or when the simulated server has no more answers.
  3. The last-page case comes first, because the general 200 case would also match it.
  4. The two server errors are not in a row: a successful page between them resets the counter. So the download finishes with done.
  5. A real script would sleep for retry_after seconds and use a growing backoff for server errors (module 16).

Alternative: split the policy from the loop: a match that returns an action word ("next", "retry", "stop") and a small loop that acts on it. Module 05 shows how to put the match into a function.

M03-X05 · Churn rate by contract from the raw CSV

Section titled “M03-X05 · Churn rate by contract from the raw CSV”
Challenge

Read data/customers.csv as plain text. Split each line on commas. Count the customers and the churned customers per contract type, and print the churn rate of each contract, from highest to lowest. Also count the customers whose total_charges field is empty. Use only loops, if, string methods and dicts.

Expected output
month-to-month 823 of 2784 29.6%
one-year 108 of 1225 8.8%
two-year 32 of 991 3.2%
Blank total_charges: 10
Starter
from pathlib import Path
lines = Path("data/customers.csv").read_text(encoding="utf-8").splitlines()
header = lines[0].split(",")
contract_col = header.index("contract")
# TODO: find the columns of churned and total_charges the same way
customers = {}
churned = {}
blank_total = 0
# TODO: loop over the data lines (skip the header)
# TODO: update the two dicts and blank_total
# TODO: print one line per contract, from the highest churn rate to the lowest
Hint 1

lines[1:] skips the header. fields = line.split(",") gives the columns. header.index("churned") gives the position of a column name.

Hint 2

For each line: if the contract is not in customers yet, set both counts to 0. Then add 1 to customers[contract] and add int(fields[churn_col]) to churned[contract].

Hint 3

You know the three contract types after the loop. To print from high to low without sorted() and a key (module 05), loop over the contracts, find the highest remaining rate, print it and remove it, three times.

Solution
from pathlib import Path
lines = Path("data/customers.csv").read_text(encoding="utf-8").splitlines()
header = lines[0].split(",")
contract_col = header.index("contract")
churn_col = header.index("churned")
total_col = header.index("total_charges")
customers = {}
churned = {}
blank_total = 0
for line in lines[1:]:
fields = line.split(",")
contract = fields[contract_col]
if contract not in customers:
customers[contract] = 0
churned[contract] = 0
customers[contract] += 1
churned[contract] += int(fields[churn_col])
if not fields[total_col]:
blank_total += 1
rates = {}
for contract in customers:
rates[contract] = churned[contract] / customers[contract]
while rates:
top = None
for contract in rates:
if top is None or rates[contract] > rates[top]:
top = contract
print(f"{top:<15} {churned[top]:>4} of {customers[top]:>4} {rates[top]:.1%}")
del rates[top]
print("Blank total_charges:", blank_total)
assert sum(customers.values()) == 5000
assert sum(churned.values()) == 963
assert blank_total == 10
Output
month-to-month 823 of 2784 29.6%
one-year 108 of 1225 8.8%
two-year 32 of 991 3.2%
Blank total_charges: 10

How it works:

  1. header.index(...) finds each column by name, so the code does not depend on the column order.
  2. The first time a contract appears, both of its counters start at 0. int(fields[churn_col]) adds 1 for a churned customer and 0 otherwise.
  3. An empty total_charges field is the empty string, which is falsy. The 10 brand-new customers have one.
  4. The while rates: loop runs until the dict is empty. Each pass finds the highest remaining rate with a max-tracking loop, prints it and deletes it with del.
  5. The asserts check the totals against the data dictionary: 5,000 customers, 963 churned. The rates match it too: 29.6%, 8.8% and 3.2%.

Alternative: sorted(rates, key=rates.get, reverse=True) sorts the contracts by rate in one call (module 05). For real CSV files, use the csv module (module 07) or pandas (module 24): plain split(",") breaks on quoted fields that contain commas.