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:
- Read the task and the expected output (or the acceptance criteria).
- Copy the starter code into a script, for example
exercise.py, and replace each to-do comment with your code. - Run it with
python exercise.pyfrom your project folder, so thatdata/is found. Compare your output with the expected output. - 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
Section titled “Warm-up”M03-W01 · Label a temperature
Section titled “M03-W01 · Label a temperature”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.
18.7 °C: too cold23.0 °C: normal23.6 °C: too warmreadings = [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 passHint 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"]18.7 °C: too cold23.0 °C: normal23.6 °C: too warmHow it works:
- The loop gives each reading to the
ifchain in turn. - Python reaches the
elifonly when the reading is 19.0 or more, soreading <= 23.0is enough for the “normal” band. - The boundary value 23.0 passes
<= 23.0, so it isnormal. - 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”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.
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 codeHint 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}False True False TrueFalse True False FalseHow it works:
[]and{}are empty, so they are falsy.[0]holds one item and{"churned": 0}holds one key. Both are truthy. Truthiness looks at the container, not at the falsy item inside.""is empty and falsy." "holds a space and is truthy.Noneand0.0are 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”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.
C00001: 0 ticketsC00003: 1 ticketC00286: 4 ticketscustomer_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 passHint 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"]C00001: 0 ticketsC00003: 1 ticketC00286: 4 ticketsHow it works:
zip()pairs each id with its ticket count.- The conditional expression gives
"ticket"only when the count is exactly 1. English uses the plural for 0 too. - 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()”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.
00:0000:1000:2000:3000:4000:50# TODO: loop over the minutes 0, 10, ..., 50 with range()# TODO: print each time as 00:MMHint 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) == 6assert times[-1] == "00:50"00:0000:1000:2000:3000:4000:50How it works:
range(0, 60, 10)gives 0, 10, 20, 30, 40 and 50. The stop, 60, is excluded.:02dshows each number with at least 2 digits, so 0 becomes00.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()”Print the five Electronics products of data/products.csv as a numbered list that starts at 1.
1. Wireless Earbuds2. Noise-Cancelling Headphones3. 55-inch 4K Smart TV4. 14-inch Ultrabook Laptop5. Smartwatch Series 5products = [ "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 = 0for number, product in enumerate(products, start=1): print(f"{number}. {product}") last_number = numberassert last_number == len(products)1. Wireless Earbuds2. Noise-Cancelling Headphones3. 55-inch 4K Smart TV4. 14-inch Ultrabook Laptop5. Smartwatch Series 5How it works:
enumerate(products, start=1)gives(1, "Wireless Earbuds"),(2, "Noise-Cancelling Headphones")and so on.for number, product in ...unpacks each pair.- 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()”Two parallel lists hold the first four store ids and their cities from data/stores.csv. Print one line per store.
S01 ChicagoS02 MinneapolisS03 DetroitS04 Houstonstore_ids = ["S01", "S02", "S03", "S04"]cities = ["Chicago", "Minneapolis", "Detroit", "Houston"]# TODO: loop over both lists together and print "S01 Chicago" and so onHint 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 = 0for store_id, city in zip(store_ids, cities, strict=True): print(store_id, city) pairs += 1assert pairs == 4S01 ChicagoS02 MinneapolisS03 DetroitS04 HoustonHow it works:
zip()takes the first item of each list, then the second, and so on.- Each pair is unpacked into
store_idandcity. strict=Truechecks 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”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.
discounts = [0.05, 0.0, 0.0, 0.0, 0.1, 0.0, 0.1, 0.05]big_discounts = 0for discount in discounts: if discount == 0.1 or 0.2: # TODO: fix this condition big_discounts += 1print("Lines with 10% or 20% off:", big_discounts)Lines with 10% or 20% off: 2Hint 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 = 0for discount in discounts: if discount == 0.1 or discount == 0.2: big_discounts += 1print("Lines with 10% or 20% off:", big_discounts)assert big_discounts == 2Lines with 10% or 20% off: 2How it works:
- In the bug,
discount == 0.1 or 0.2is0.2whenever the comparison is false.0.2is truthy, so theifblock runs for every line. - With both comparisons written in full, only the two lines with 0.1 count. No line in this sample has 0.2.
- 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”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.
200 ok404 not found429 rate limited500 server error302 othercodes = [200, 404, 429, 500, 302]for code in codes: # TODO: use match-case with literal patterns, an or-pattern and _ passHint 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"200 ok404 not found429 rate limited500 server error302 otherHow it works:
- Each literal pattern compares the subject
codewith==. - The or-pattern
500 | 502 | 503groups three server errors into one case. 302matches 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”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.
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 codeHint 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 = 0for line in lines: if not line: continue if line == "STOP": break print("line:", line) printed += 1print("done")assert printed == 3line: 21.0line: 21.9line: n/adoneHow it works:
"21.0"is printed.""is falsy, socontinueskips it."21.9"and"n/a"are printed. This loop does not validate numbers."STOP"triggersbreak, so"21.4"is never reached.doneruns after the loop.
Alternative: none needed; the point is to trace the flow by hand.
M03-C01 · Find the hottest valid reading
Section titled “M03-C01 · Find the hottest valid reading”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.
Hottest: 22.9 °C on line 8from pathlib import Path
lines = Path("data/readings.txt").read_text(encoding="utf-8").splitlines()highest = Nonehighest_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 higherHint 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 = Nonehighest_line = Nonefor 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.9assert highest_line == 8Hottest: 22.9 °C on line 8How it works:
enumerate(..., start=1)gives editor line numbers.- The
continueexit skips the 3 broken lines beforefloat()sees them. highest is Nonehandles the first valid reading, because nothing can be compared withNone. Short-circuit evaluation then skipsvalue > highest.- 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”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.
C02677 highC03943 highC04339 lowC00286 mediumC04557 low{'high': 2, 'medium': 1, 'low': 2}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 countsHint 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}C02677 highC03943 highC04339 lowC00286 mediumC04557 low{'high': 2, 'medium': 1, 'low': 2}How it works:
- C02677 is month-to-month with 3 tickets, and C03943 is month-to-month with 6 months of tenure. Both are
high. - C00286 has 4 tickets but a two-year contract, so it is not
high. Theelifcatches it asmedium. - C04339 has short tenure, but on a one-year contract with many logins it is
low. C04557 islowtoo. - Without the parentheses,
andbinds tighter thanor, and every customer with 3 or more tickets would behigh, 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”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.
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)C00077 0C00001 17(no id) unknownHint 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"]C00077 0C00001 17(no id) unknownHow it works:
0 or "unknown"gives"unknown", because 0 is falsy. That is the bug."unknown" if raw is None else rawreplaces onlyNone. A real 0 stays 0.- 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.
M03-C04 · Fix the bug: zip drops a line
Section titled “M03-C04 · Fix the bug: zip drops a line”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.
unit_prices = [59.99, 249.00, 1149.00]quantities = [1, 1] # TODO: one value is missingdiscounts = [0.0, 0.1, 0.05]total = 0.0for 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=Trueand the broken data, the loop raisesValueError: 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)59.99 1 0.0249.0 1 0.1ValueError: zip() argument 2 is shorter than argument 1The fix:
import math
unit_prices = [59.99, 249.00, 1149.00]quantities = [1, 1, 2]discounts = [0.0, 0.1, 0.05]total = 0.0for 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)Total: 2467.19 USDHow it works:
- Without
strict=True,zip()gives only two triples and silently drops the laptop line, the most expensive one. - With
strict=True, the same data raisesValueError: zip() argument 2 is shorter than argument 1. The error names the short list. - 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.
M03-C05 · Years until revenue doubles
Section titled “M03-C05 · Years until revenue doubles”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.
2025: 2,313,808 USD2026: 2,744,176 USD2027: 3,254,593 USD2028: 3,859,947 USD2029: 4,577,898 USDDoubled in 2029revenue = 1_950_934.24target = 2 * revenueyear = 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 :,.0fHint 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.24target = 2 * revenueyear = 2024while revenue < target: revenue *= 1.186 year += 1 print(f"{year}: {revenue:,.0f} USD")print("Doubled in", year)assert year == 2029assert revenue >= target2025: 2,313,808 USD2026: 2,744,176 USD2027: 3,254,593 USD2028: 3,859,947 USD2029: 4,577,898 USDDoubled in 2029How it works:
- The loop runs while revenue is below the target. You do not know the number of years in advance, which is why
whilefits. - Each iteration multiplies by 1.186 and counts one year.
- 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.
M03-C06 · Retry a request with backoff
Section titled “M03-C06 · Retry a request with backoff”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.
attempt 1: 503, wait 1 sattempt 2: 503, wait 2 sattempt 3: 200 ok---attempt 1: 503, wait 1 sattempt 2: 500, wait 2 sattempt 3: 503, wait 4 sgiving up---backoff_seconds = [1, 2, 4]max_attempts = 3for 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 = 3results = []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"]attempt 1: 503, wait 1 sattempt 2: 503, wait 2 sattempt 3: 200 ok---attempt 1: 503, wait 1 sattempt 2: 500, wait 2 sattempt 3: 503, wait 4 sgiving up---How it works:
- The outer
forruns two scenarios. The innerwhileis the retry loop. - On a 200,
breakleaves thewhile, and theelseblock is skipped. - When all 3 attempts fail, the condition
attempt < max_attemptsbecomes false. The loop ends normally, so theelseblock printsgiving up. - 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”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.
welcome C04991Net revenue: 2243.09 USDSignups: 1Problems: [{'type': 'order', 'order_id': 'O000007'}, {'type': 'ping'}]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.0signups = 0problems = []# TODO: match each event and update the three accumulatorsHint 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.0signups = 0problems = []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) == 2welcome C04991Net revenue: 2243.09 USDSignups: 1Problems: [{'type': 'order', 'order_id': 'O000007'}, {'type': 'ping'}]How it works:
- Each mapping pattern checks the
"type"and the keys that the case needs, then captures the values. float(amount) | int(amount)combines two class patterns: it accepts a whole-number amount such as100as well as284.09, and rejects an amount sent as text, such as"284.09". Withfloat(amount)alone, a valid amount of100would end up inproblems, because100is anint, not afloat.- The order O000007 has no
"amount", so no order case matches. It ends inproblemswith the unknown"ping"event. - 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”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.
full report for S01report for S07 in 2024-05list the 12 storesshow helpusage error: reportshow helpcommands = [ ["report", "S01"], ["report", "S07", "--month", "2024-05"], ["stores"], ["help"], ["report"], [],]for words in commands: # TODO: match words against sequence patterns passHint 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"full report for S01report for S07 in 2024-05list the 12 storesshow helpusage error: reportshow helpHow it works:
- Each sequence pattern fixes the number of words and the literal words, and captures the rest.
["report"]alone has one word, so neither report pattern matches. It falls tocase _.- The empty list matches
[]in the or-pattern and shows the help, as many tools do. ' '.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”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.
Home: P006 is out of stockElectronics: fully in stockitems = [ ("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" passHint 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"]Home: P006 is out of stockElectronics: fully in stockHow it works:
- The outer loop picks a category. The inner loop searches the items.
- For
Home, P006 has stock 0.breakends the inner loop only, and the outer loop moves on. - For
Electronics, no item matches. The inner loop ends normally, so itselseblock 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"].
M03-C10 · Refactor: replace index loops
Section titled “M03-C10 · Refactor: replace index loops”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.
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()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 = 0for number, (time, temperature, humidity) in enumerate(rows, start=1): print(f"{number}. {time} {temperature:.2f} °C {humidity:.1f} %") count = numberassert count == 31. 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:
zip()builds the triples.strict=Trueadds a length check that the index version did not have.enumerate(rows, start=1)adds the number and removes thei + 1.- The parentheses in
(time, temperature, humidity)unpack the inner triple in the same line. - 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.
M03-C11 · Choose the loop and justify it
Section titled “M03-C11 · Choose the loop and justify it”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.
- The mean of the 10 readings.
- 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?
- The first reading above 22.6 °C, or a “none” message.
1. Mean: 22.06 °C2. Below the reorder point after 11 days (15 units left)3. First reading above 22.6: 22.9 (line 8)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 3Hint 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.0for reading in readings: total += readingmean = total / len(readings)print(f"1. Mean: {mean:.2f} °C")
# 2. Unknown number of repetitions: a while loop.days = 0while stock >= 20: stock -= 7 days += 1print(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})") breakelse: print("3. No reading above 22.6")
assert days == 11 and stock == 151. Mean: 22.06 °C2. Below the reorder point after 11 days (15 units left)3. First reading above 22.6: 22.9 (line 8)How it works:
- Mean: the loop visits each reading once, so
forfits. In real code,sum(readings) / len(readings)is shorter. - 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.
- Search:
for-elsestops 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”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.
threshold 0.3: 4 TP, 2 FP, cost USD 30threshold 0.5: 3 TP, 1 FP, cost USD 320threshold 0.7: 2 TP, 0 FP, cost USD 610Cheapest: threshold 0.3 (USD 30)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 thresholdHint 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, 300results = []best_threshold, best_cost = None, Nonefor 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, costprint(f"Cheapest: threshold {best_threshold} (USD {best_cost})")assert results == [(4, 2), (3, 1), (2, 0)]assert best_threshold == 0.3threshold 0.3: 4 TP, 2 FP, cost USD 30threshold 0.5: 3 TP, 1 FP, cost USD 320threshold 0.7: 2 TP, 0 FP, cost USD 610Cheapest: threshold 0.3 (USD 30)How it works:
- The counters are reset at the start of each outer iteration. Otherwise, each threshold would add to the previous counts.
continueskips the customers who are not flagged.missedis the number of churners below the threshold. The cost adds USD 5 per call and USD 300 per missed churner.- 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
Section titled “Challenge”M03-X01 · Longest warm streak
Section titled “M03-X01 · Longest warm streak”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.
Longest run above 22.0 °C: 5 readingsFrom line 7 to line 11from 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 runHint 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 = 0run_start = 0best_length = 0best_start = 0best_end = 0for 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_lengthassert (best_start, best_end) == (7, 11)Longest run above 22.0 °C: 5 readingsFrom line 7 to line 11How it works:
validuses short-circuit evaluation: for an empty line,bool(text)isFalse, and.isdigit()is never called. In theif,not valid or ...protectsfloat(text)the same way.- Every line that is broken or not warm resets the current run and leaves the iteration with
continue. - 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.
- 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. - 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”A shop sends events with nested data. Process them with one match statement per event:
orderwith astore_idand a non-emptylineslist: add the line amounts to that store.orderwith an emptylineslist: a problemempty order O....refundwith a positive amount: subtract it from that store.refundwith an amount of 0 or less: a problembad 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.
S07: 2183.10 USDS09: 146.95 USDS11: 59.99 USDProblems: ['empty order O999998', 'bad refund O999999', 'unknown event']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 problemsHint 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) == 3S07: 2183.10 USDS09: 146.95 USDS11: 59.99 USDProblems: ['empty order O999998', 'bad refund O999999', 'unknown event']How it works:
"lines": []matches only an empty list, so the empty test order O999998 becomes a problem before the general order case can see it.[first, *rest]matches a list with at least one amount. The loop addsfirstand then every item ofrest.- The guard
if amount > 0lets only positive refunds through. The refund of −5.0 falls to the next case, which reports it. - The
shipmentevent matches no order or refund pattern, socase _reports it. 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.
M03-X03 · Search for a learning rate
Section titled “M03-X03 · Search for a learning rate”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.
rate 0.01: not converged after 200 iterations, w = 3.037rate 0.1: converged after 28 iterations, w = 3.037rate 0.3: converged after 12 iterations, w = 3.037rate 0.6: diverged after 32 iterations, w = -1.283e+06Fastest: rate 0.3 (12 iterations)sizes = [0.8, 1.2, 1.5, 2.0]prices = [2.5, 3.5, 4.6, 6.1]max_iter = 200best_rate = Nonebest_iterations = Nonefor 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 onesHint 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 = 200best_rate = Nonebest_iterations = Nonefor 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.3rate 0.01: not converged after 200 iterations, w = 3.037rate 0.1: converged after 28 iterations, w = 3.037rate 0.3: converged after 12 iterations, w = 3.037rate 0.6: diverged after 32 iterations, w = -1.283e+06Fastest: rate 0.3 (12 iterations)How it works:
- Three nested levels: the rates (
for), the training (while) and the gradient sum (for). - The two
breakstatements leave thewhileearly. Thestatusvariable records why. The loopelsecovers the third outcome: the limit was reached. - A rate of 0.01 moves too slowly: after 200 iterations
wis 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. :.4gshows 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”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:
200with anextURL: count the items and continue.200withnextset toNone: count the items and stop withdone.429withretry_after: add the wait to a total wait time and retry.5xx: retry, but stop withfailedafter 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.
page 1: 3 itemsrate limited: wait 30 sserver error 503 (1 in a row)page 2: 2 itemsserver error 503 (1 in a row)page 3: 2 items, last pagedone: 7 items, 6 requests, 30 s waitedresponses = [ {"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 = 0items = 0waited = 0server_errors_in_a_row = 0outcome = None# TODO: while outcome is None: take the next response and match itHint 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 = 10requests_sent = 0items = 0waited = 0server_errors_in_a_row = 0outcome = 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 == 7page 1: 3 itemsrate limited: wait 30 sserver error 503 (1 in a row)page 2: 2 itemsserver error 503 (1 in a row)page 3: 2 items, last pagedone: 7 items, 6 requests, 30 s waitedHow it works:
- The
whileconditionoutcome is Nonekeeps the loop going until a case sets an outcome. - The guard at the top is the safety limit: it ends the loop after
max_requestsrequests, or when the simulated server has no more answers. - The last-page case comes first, because the general 200 case would also match it.
- The two server errors are not in a row: a successful page between them resets the counter. So the download finishes with
done. - A real script would sleep for
retry_afterseconds 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”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.
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: 10from 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 waycustomers = {}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 lowestHint 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 = 0for 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()) == 5000assert sum(churned.values()) == 963assert blank_total == 10month-to-month 823 of 2784 29.6%one-year 108 of 1225 8.8%two-year 32 of 991 3.2%Blank total_charges: 10How it works:
header.index(...)finds each column by name, so the code does not depend on the column order.- 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. - An empty
total_chargesfield is the empty string, which is falsy. The 10 brand-new customers have one. - 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 withdel. - 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.