Skip to content

06. Errors and debugging — Exercises

These exercises practice every idea of the Errors and debugging lesson. Most of them use the messy course files: data/sales_raw.csv, data/readings.txt, data/sensors.csv, data/config.json and data/logs/app.log.

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 the script with python exercise.py from your project folder, the one that holds data/.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Several solutions print log messages. Logging writes to stderr, the error stream of the terminal. Your terminal shows stderr and stdout together, so you see the same lines as in the Output blocks.

Warm-up

Predict the output: each line of the starter runs one failing operation and prints the name of the exception type. Write down the name for each line before you run the code.

Acceptance criteria:

  • Write your prediction line by line, then run the code.
  • Your prediction matches the Output in the solution: six exception names, one per line.
Starter
def error_name(operation):
try:
operation()
except Exception as err:
return type(err).__name__
product = {"product_id": "P001", "unit_price": 79.99}
readings = [21.7, 22.1, 21.9]
print(error_name(lambda: int("21.7")))
print(error_name(lambda: product["price"]))
print(error_name(lambda: readings[3]))
print(error_name(lambda: product["unit_price"] + "USD"))
print(error_name(lambda: product.upper()))
print(error_name(lambda: 1375 / (3 - 3)))
# TODO: write your six predictions before you run the code
Hint 1

A dict raises one error for a missing key, a list another one for a position that does not exist.

Hint 2

79.99 + "USD" mixes two types. product.upper() asks a dict for a method that only strings have.

Solution
def error_name(operation):
try:
operation()
except Exception as err:
return type(err).__name__
product = {"product_id": "P001", "unit_price": 79.99}
readings = [21.7, 22.1, 21.9]
print(error_name(lambda: int("21.7")))
print(error_name(lambda: product["price"]))
print(error_name(lambda: readings[3]))
print(error_name(lambda: product["unit_price"] + "USD"))
print(error_name(lambda: product.upper()))
print(error_name(lambda: 1375 / (3 - 3)))
assert error_name(lambda: int("21.7")) == "ValueError"
assert issubclass(KeyError, LookupError) and issubclass(IndexError, LookupError)
Output
ValueError
KeyError
IndexError
TypeError
AttributeError
ZeroDivisionError

How it works:

  1. int("21.7") gets a string, the right type, but the text is not a whole number: ValueError.
  2. The dict has no key "price": KeyError. A list of 3 items has no position 3: IndexError. Both are kinds of LookupError.
  3. A float plus a string is an operation on the wrong types: TypeError.
  4. A dict has no upper attribute: AttributeError.
  5. 3 - 3 is 0, so the division raises ZeroDivisionError.

Alternative: print f"{type(err).__name__}: {err}" in error_name to see the messages too. The message of a KeyError is only the key, 'price'.

Warm-up

Write to_float(text). It returns the float value of text, or None when the text is not a number. Use try/except and catch only ValueError. Test it on four raw lines of data/readings.txt.

Expected output
'21.7' -> 21.7
'error' -> None
'' -> None
' 22.4 ' -> 22.4
Starter
def to_float(text):
# TODO: return float(text), or None when the conversion fails
pass
for raw in ["21.7", "error", "", " 22.4 "]:
print(f"{raw!r} -> {to_float(raw)}")
Hint 1

Put return float(text) inside a try block.

Hint 2

In the except ValueError: block, return None. float() ignores spaces around the digits by itself.

Solution
def to_float(text):
try:
return float(text)
except ValueError:
return None
for raw in ["21.7", "error", "", " 22.4 "]:
print(f"{raw!r} -> {to_float(raw)}")
assert to_float("n/a") is None
assert to_float("19.3") == 19.3
Output
'21.7' -> 21.7
'error' -> None
'' -> None
' 22.4 ' -> 22.4

How it works:

  1. When float(text) works, the return inside try returns the number.
  2. When it raises ValueError, Python jumps to the except block, which returns None.
  3. float("") raises ValueError too, so the empty line gives None.
  4. Only ValueError is caught. to_float(None) would still raise a TypeError, which tells you that the caller passed the wrong kind of value.

Alternative: return a default that the caller chooses: def to_float(text, default=None). Never use 0.0 as the default for sensor data; a reading of 0 °C is a real temperature.

M06-W03 · Fix the bug: read the last line

Section titled “M06-W03 · Fix the bug: read the last line”
Warm-up

Fix the bug: this function computes the revenue of one line of data/sales.csv, but it crashes. Read the last traceback line, then fix the code.

def line_total(row):
return row["unit price"] * row["quantity"] * (1 - row["discount"])
row = {"order_id": "O000004", "product_id": "P002", "unit_price": 249.0,
"quantity": 1, "discount": 0.1}
print(line_total(row))
Output
KeyError: 'unit price'
Expected output
224.1
Starter
def line_total(row):
return row["unit price"] * row["quantity"] * (1 - row["discount"]) # TODO: fix
row = {"order_id": "O000004", "product_id": "P002", "unit_price": 249.0,
"quantity": 1, "discount": 0.1}
print(round(line_total(row), 2))
Hint 1

A KeyError message is the key that was not found. Compare it with the keys of row.

Solution
def line_total(row):
return row["unit_price"] * row["quantity"] * (1 - row["discount"])
row = {"order_id": "O000004", "product_id": "P002", "unit_price": 249.0,
"quantity": 1, "discount": 0.1}
print(round(line_total(row), 2))
assert round(line_total(row), 2) == 224.1
Output
224.1

How it works:

  1. The last line KeyError: 'unit price' names the missing key: it has a space.
  2. The dict key is "unit_price", with an underscore, as in the CSV header.
  3. round(..., 2) hides the float error in 249.0 * 0.9.

Alternative: print sorted(row) when a KeyError surprises you. It lists the real keys, so a typo is easy to spot.

M06-W04 · Predict the output: the order of the clauses

Section titled “M06-W04 · Predict the output: the order of the clauses”
Warm-up

Predict the output: the function below has all four clauses. Write down every line that the two calls print, in order.

Acceptance criteria:

  • Write your prediction line by line, then run the code.
  • Your prediction matches the Output in the solution, including the lines from finally.
Starter
def parse(raw):
try:
value = int(raw)
except ValueError:
print("except")
value = 0
else:
print("else")
finally:
print("finally")
print("after", value)
parse("4")
parse("four")
# TODO: write your prediction before you run the code
Hint 1

else runs only when the try block raised nothing. except runs only when it raised a matching exception.

Hint 2

finally runs in both cases, before the line after the try statement.

Solution
def parse(raw):
try:
value = int(raw)
except ValueError:
print("except")
value = 0
else:
print("else")
finally:
print("finally")
print("after", value)
parse("4")
parse("four")
assert int("4") == 4
Output
else
finally
after 4
except
finally
after 0

How it works:

  1. parse("4"): int("4") works, so else runs, then finally, then the line after the statement.
  2. parse("four"): int("four") raises ValueError. except runs and sets value = 0. else is skipped. finally runs, then the last line.

Alternative: add print("try") as the first line of the try block to see that it always starts.

M06-W05 · Raise a ValueError with a clear message

Section titled “M06-W05 · Raise a ValueError with a clear message”
Warm-up

The pipeline config data/config.json allows a discount of at most 0.2. Write check_discount(discount). It returns the discount when it is from 0 to 0.2, and raises a ValueError with the message shown otherwise. Test it with 0.1 and 0.25.

Expected output
0.1 ok
ValueError: discount must be from 0 to 0.2, got 0.25
Starter
MAX_DISCOUNT = 0.2
def check_discount(discount):
# TODO: raise ValueError(...) when discount is outside 0 to MAX_DISCOUNT
return discount
print(check_discount(0.1), "ok")
try:
check_discount(0.25)
except ValueError as err:
print(f"ValueError: {err}")
Hint 1

A chained comparison checks the range: 0 <= discount <= MAX_DISCOUNT.

Hint 2

raise ValueError(f"discount must be from 0 to {MAX_DISCOUNT}, got {discount}").

Solution
MAX_DISCOUNT = 0.2
def check_discount(discount):
if not 0 <= discount <= MAX_DISCOUNT:
raise ValueError(f"discount must be from 0 to {MAX_DISCOUNT}, got {discount}")
return discount
print(check_discount(0.1), "ok")
try:
check_discount(0.25)
except ValueError as err:
print(f"ValueError: {err}")
assert check_discount(0.0) == 0.0
Output
0.1 ok
ValueError: discount must be from 0 to 0.2, got 0.25

How it works:

  1. not 0 <= discount <= MAX_DISCOUNT is True for values below 0 or above 0.2.
  2. raise stops the function. The caller’s except ValueError as err catches it, and str(err) is the message.
  3. The message says what was expected and what arrived.

Alternative: raise a custom exception type that stores the limit as an attribute, so a handler can read it without parsing the message. Exercise M06-W07 shows how to define one.

Warm-up

The dict below has four stores from data/stores.csv. Write region_of(store_id). It returns the region, or "Unknown" when the store id is not in the dict. Use try/except KeyError.

Expected output
S01 North
S07 East
S13 Unknown
Starter
STORE_REGIONS = {"S01": "North", "S04": "South", "S07": "East", "S10": "West"}
def region_of(store_id):
# TODO: return the region, or "Unknown" for a store that is not in the dict
pass
for store_id in ["S01", "S07", "S13"]:
print(store_id, region_of(store_id))
Hint 1

STORE_REGIONS[store_id] raises KeyError for "S13".

Solution
STORE_REGIONS = {"S01": "North", "S04": "South", "S07": "East", "S10": "West"}
def region_of(store_id):
try:
return STORE_REGIONS[store_id]
except KeyError:
return "Unknown"
for store_id in ["S01", "S07", "S13"]:
print(store_id, region_of(store_id))
assert region_of("S10") == "West"
assert region_of("s01") == "Unknown" # case matters
Output
S01 North
S07 East
S13 Unknown

How it works:

  1. For a known id, the lookup works and the function returns inside try.
  2. For "S13", the lookup raises KeyError and the except block returns "Unknown".

Alternative: STORE_REGIONS.get(store_id, "Unknown") does the same in one call. Use get() when a missing key is normal. Use try/except when you need to do more than return a default, such as log the missing id.

Warm-up

data/sales_raw.csv has six negative quantities. Define NegativeQuantityError as a subclass of ValueError. Write check_quantity(quantity) that raises it for a quantity below 0. Show that a caller can catch it as a ValueError.

Expected output
caught NegativeQuantityError: quantity is negative: -3
True
Starter
# TODO: define NegativeQuantityError as a subclass of ValueError
def check_quantity(quantity):
# TODO: raise NegativeQuantityError for a quantity below 0
return quantity
try:
check_quantity(-3)
except ValueError as err:
print(f"caught {type(err).__name__}: {err}")
print(issubclass(NegativeQuantityError, ValueError))
Hint 1

A class with only a docstring is enough: class Name(Base): and an indented docstring.

Hint 2

raise NegativeQuantityError(f"quantity is negative: {quantity}").

Solution
class NegativeQuantityError(ValueError):
"""A quantity is below 0, for example a return booked as a sale."""
def check_quantity(quantity):
if quantity < 0:
raise NegativeQuantityError(f"quantity is negative: {quantity}")
return quantity
try:
check_quantity(-3)
except ValueError as err:
print(f"caught {type(err).__name__}: {err}")
print(issubclass(NegativeQuantityError, ValueError))
assert check_quantity(2) == 2
Output
caught NegativeQuantityError: quantity is negative: -3
True

How it works:

  1. class NegativeQuantityError(ValueError): makes a new, more specific kind of ValueError.
  2. except ValueError matches the type and all its subclasses, so it catches the new error.
  3. type(err).__name__ shows the real, specific type.

Alternative: subclass Exception instead, if callers should not mix this error up with other ValueErrors. Subclassing ValueError is useful when existing code already catches ValueError for bad values.

Warm-up

Configure logging with the level WARNING and the format %(levelname)s: %(message)s. Send the messages to sys.stdout, as a small report script does when its log lines are its output and should go through a pipe such as python report.py > report.txt. Then log the five messages from the starter, one at each level. Only three of them appear.

Expected output
WARNING: 23 rows with missing customer_id
ERROR: failed to parse data/reports/2024-04.csv
CRITICAL: database unreachable, aborting
Starter
import logging
import sys
# TODO: logging.basicConfig(...) with level, format, stream and force=True
log = logging.getLogger("pipeline")
log.debug("raw header read")
log.info("loaded 1200 rows")
log.warning("23 rows with missing customer_id")
log.error("failed to parse data/reports/2024-04.csv")
log.critical("database unreachable, aborting")
Hint 1

basicConfig() takes the keyword arguments level, format, stream and force.

Hint 2

stream=sys.stdout sends the lines to standard output. force=True replaces any setup that ran before.

Solution
import logging
import sys
logging.basicConfig(
level=logging.WARNING,
format="%(levelname)s: %(message)s",
stream=sys.stdout,
force=True,
)
log = logging.getLogger("pipeline")
log.debug("raw header read")
log.info("loaded 1200 rows")
log.warning("23 rows with missing customer_id")
log.error("failed to parse data/reports/2024-04.csv")
log.critical("database unreachable, aborting")
assert log.getEffectiveLevel() == logging.WARNING
Output
WARNING: 23 rows with missing customer_id
ERROR: failed to parse data/reports/2024-04.csv
CRITICAL: database unreachable, aborting

How it works:

  1. The root logger’s level is WARNING (30). DEBUG (10) and INFO (20) are below it, so they are dropped.
  2. The logger pipeline has no level of its own, so it uses the root level. getEffectiveLevel() returns that level.
  3. The format puts the level name before each message.

Alternative: leave out stream, and the lines go to stderr, the usual place for logs. Then python report.py > report.txt leaves the file empty and still shows the lines in the terminal, because > redirects only stdout.

M06-C01 · Average the sensor readings, skipping blanks

Section titled “M06-C01 · Average the sensor readings, skipping blanks”
Core

The column temperature_c of data/sensors.csv has 22 blank cells. Read the file with csv.DictReader, convert each temperature with float() and catch the ValueError for blanks. Print the number of blanks and the mean temperature per sensor, with 2 decimals.

Expected output
blank temperatures: 22
S1: 22.05 °C (2010 readings)
S2: 24.60 °C (2012 readings)
S3: 23.53 °C (2010 readings)
S4: 26.04 °C (2010 readings)
Starter
import csv
totals = {} # sensor_id -> [sum, count]
blanks = 0
with open("data/sensors.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
# TODO: convert row["temperature_c"]; count blanks; add valid values
pass
print("blank temperatures:", blanks)
# TODO: print "S1: 22.05 °C" and so on, in sensor order
Hint 1

Put only value = float(row["temperature_c"]) in the try block. Use else to add the value to the totals.

Hint 2

totals.setdefault(sensor_id, [0.0, 0]) returns the list for a sensor and creates it the first time.

Solution
import csv
totals = {} # sensor_id -> [sum, count]
blanks = 0
with open("data/sensors.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
try:
value = float(row["temperature_c"])
except ValueError:
blanks += 1
else:
pair = totals.setdefault(row["sensor_id"], [0.0, 0])
pair[0] += value
pair[1] += 1
print("blank temperatures:", blanks)
for sensor_id in sorted(totals):
total, count = totals[sensor_id]
print(f"{sensor_id}: {total / count:.2f} °C ({count} readings)")
assert blanks == 22
assert sum(count for _, count in totals.values()) == 8064 - 22
Output
blank temperatures: 22
S1: 22.05 °C (2010 readings)
S2: 24.60 °C (2012 readings)
S3: 23.53 °C (2010 readings)
S4: 26.04 °C (2010 readings)

How it works:

  1. csv.DictReader gives each row as a dict of strings. A blank cell is the empty string.
  2. float("") raises ValueError, so the except block counts it.
  3. else runs only after a successful conversion, so only real values reach the totals.
  4. The means match the data dictionary: S4 runs hottest, S1 coolest.

Alternative: test if row["temperature_c"] == "": before converting (LBYL). It works for blanks, but a cell such as "n/a" would still crash. The try version handles every non-number.

M06-C02 · Fix the bug: a too-broad except

Section titled “M06-C02 · Fix the bug: a too-broad except”
Core

Fix the bug: this function should total the revenue of three sales lines, but it returns 0.0 and shows no error. Find the real problem, then make the except clause narrow enough that such problems can never hide again. Missing revenue values ("") must still count as 0.

def total_revenue(rows):
total = 0.0
for row in rows:
try:
total += float(row["revenu"])
except Exception:
pass
return total
rows = [
{"order_id": "O000004", "product_id": "P002", "revenue": "224.1"},
{"order_id": "O000005", "product_id": "P022", "revenue": "29.99"},
{"order_id": "O000009", "product_id": "P012", "revenue": "179.0"},
]
print(total_revenue(rows))
Output
0.0
Expected output
Total: 433.09
Starter
def total_revenue(rows):
total = 0.0
for row in rows:
try:
total += float(row["revenu"])
except Exception: # TODO: catch only what a missing value raises
pass
return total
rows = [
{"order_id": "O000004", "product_id": "P002", "revenue": "224.1"},
{"order_id": "O000005", "product_id": "P022", "revenue": "29.99"},
{"order_id": "O000009", "product_id": "P012", "revenue": "179.0"},
]
print(f"Total: {total_revenue(rows):.2f}")
Hint 1

Change except Exception to except ValueError first and run it again. Read the new traceback.

Hint 2

The traceback ends with a KeyError. Which key does it name?

Solution
def total_revenue(rows):
total = 0.0
for row in rows:
try:
total += float(row["revenue"])
except ValueError: # "" or another non-number counts as 0
pass
return total
rows = [
{"order_id": "O000004", "product_id": "P002", "revenue": "224.1"},
{"order_id": "O000005", "product_id": "P022", "revenue": "29.99"},
{"order_id": "O000009", "product_id": "P012", "revenue": "179.0"},
]
print(f"Total: {total_revenue(rows):.2f}")
assert total_revenue([{"revenue": ""}]) == 0.0
Output
Total: 433.09

How it works:

  1. row["revenu"] raises KeyError on every row. except Exception caught it and pass threw it away, so the total stayed 0.0.
  2. With except ValueError, the KeyError is not caught. The traceback names the key 'revenu' at once.
  3. After the typo is fixed, except ValueError still handles the case the code was written for: float("").

Alternative: count the skipped rows instead of pass, and log or print the count. A silent pass is rarely right.

M06-C03 · Refactor: keep the try block small

Section titled “M06-C03 · Refactor: keep the try block small”
Core

Refactor this function. It wraps four lines in one try block, so a bug in the formula would be reported as “bad price”. Move everything except the conversion out of the try block, using else. The output must not change.

def clean_line(row):
try:
price = float(row["unit_price"].removeprefix("$").replace(",", ""))
quantity = int(row["quantity"])
revenue = round(price * quantity * (1 - float(row["discount"])), 2)
return {"order_id": row["order_id"], "revenue": revenue}
except ValueError:
return {"order_id": row["order_id"], "error": "bad price"}
raw = [
{"order_id": "O000145", "unit_price": "$1,299.00", "quantity": "2",
"discount": "0.0"},
{"order_id": "O002982", "unit_price": "N/A", "quantity": "2",
"discount": "0.05"},
]
for row in raw:
print(clean_line(row))
Output
{'order_id': 'O000145', 'revenue': 2598.0}
{'order_id': 'O002982', 'error': 'bad price'}
Expected output
{'order_id': 'O000145', 'revenue': 2598.0}
{'order_id': 'O002982', 'error': 'bad price'}
Starter
def clean_line(row):
try:
price = float(row["unit_price"].removeprefix("$").replace(",", ""))
except ValueError:
return {"order_id": row["order_id"], "error": "bad price"}
# TODO: use else for the quantity, revenue and return lines
Hint 1

A return inside except ends the function, so the else block only runs when the price was parsed.

Solution
def clean_line(row):
try:
price = float(row["unit_price"].removeprefix("$").replace(",", ""))
except ValueError:
return {"order_id": row["order_id"], "error": "bad price"}
else:
quantity = int(row["quantity"])
revenue = round(price * quantity * (1 - float(row["discount"])), 2)
return {"order_id": row["order_id"], "revenue": revenue}
raw = [
{"order_id": "O000145", "unit_price": "$1,299.00", "quantity": "2",
"discount": "0.0"},
{"order_id": "O002982", "unit_price": "N/A", "quantity": "2",
"discount": "0.05"},
]
for row in raw:
print(clean_line(row))
assert clean_line(raw[0])["revenue"] == 2598.0
Output
{'order_id': 'O000145', 'revenue': 2598.0}
{'order_id': 'O002982', 'error': 'bad price'}

How it works:

  1. Only the price conversion is inside try. A bad price still returns the error dict.
  2. A ValueError from int(row["quantity"]) now travels up with its own traceback instead of being called “bad price”. That is what you want: it is a different problem.
  3. The rows are lines 12 and 221 of data/sales_raw.csv.

Alternative: because except returns, you can drop the else: and write the last three lines after the try statement. Both forms are common. else makes the intent explicit.

Core

The lesson’s parse_price() turns the European text "$12,99" into 1299.0, a price 100 times too high. Extend it: after the missing-token check, raise ValueError when the text has a comma followed by exactly 2 digits at the end. Check that all 1,190 non-missing prices of data/sales_raw.csv still parse.

Expected output
'$79.99' -> 79.99
'$1,299.00' -> 1299.0
'$12,99' -> ValueError: unit_price '$12,99' uses a decimal comma
parsed 1190, rejected 10
Starter
import csv
MISSING_TOKENS = {"", "N/A", "-"}
def parse_price(text):
cleaned = text.strip()
if cleaned in MISSING_TOKENS:
raise ValueError(f"unit_price is missing ({text!r})")
# TODO: raise ValueError for a decimal comma such as "$12,99"
return float(cleaned.removeprefix("$").replace(",", ""))
for sample in ["$79.99", "$1,299.00", "$12,99"]:
try:
print(f"{sample!r} -> {parse_price(sample)}")
except ValueError as err:
print(f"{sample!r} -> ValueError: {err}")
# TODO: parse the whole unit_price column and count the results
Hint 1

cleaned[-3] is the third character from the end. For "$12,99" it is ",".

Hint 2

Check len(cleaned) >= 3 and cleaned[-3] == "," and cleaned[-2:].isdigit().

Solution
import csv
MISSING_TOKENS = {"", "N/A", "-"}
def parse_price(text):
cleaned = text.strip()
if cleaned in MISSING_TOKENS:
raise ValueError(f"unit_price is missing ({text!r})")
if len(cleaned) >= 3 and cleaned[-3] == "," and cleaned[-2:].isdigit():
raise ValueError(f"unit_price {text!r} uses a decimal comma")
return float(cleaned.removeprefix("$").replace(",", ""))
for sample in ["$79.99", "$1,299.00", "$12,99"]:
try:
print(f"{sample!r} -> {parse_price(sample)}")
except ValueError as err:
print(f"{sample!r} -> ValueError: {err}")
parsed, missing = 0, 0
with open("data/sales_raw.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
try:
parse_price(row["unit_price"])
except ValueError:
missing += 1
else:
parsed += 1
print(f"parsed {parsed}, rejected {missing}")
assert (parsed, missing) == (1190, 10)
Output
'$79.99' -> 79.99
'$1,299.00' -> 1299.0
'$12,99' -> ValueError: unit_price '$12,99' uses a decimal comma
parsed 1190, rejected 10

How it works:

  1. In "$1,299.00" the comma is the fifth character from the end, so the new check does not fire.
  2. In "$12,99" the third character from the end is a comma and the last two are digits: a decimal comma. The function raises before float() can give a wrong number.
  3. The file still parses 1,190 prices and rejects only the 10 missing ones, so the new rule breaks nothing.

Alternative: module 09 teaches regular expressions. The pattern r",\d{2}$" expresses the same rule in one line: re.search(r",\d{2}$", cleaned).

Core

Write parse_quantity(text, column="quantity"). It returns int(text). When int() fails, it raises an InvalidValueError (a subclass of Exception that you define) with the message quantity '2.5' is not a whole number, chained to the original error with from. Print the new error and the type of its __cause__.

Expected output
3
InvalidValueError: quantity '2.5' is not a whole number
cause: ValueError: invalid literal for int() with base 10: '2.5'
Starter
class InvalidValueError(Exception):
"""A cell has a value, but the value breaks a rule."""
def parse_quantity(text, column="quantity"):
# TODO: return int(text); on ValueError raise InvalidValueError(...) from err
pass
print(parse_quantity("3"))
try:
parse_quantity("2.5")
except InvalidValueError as err:
print(f"{type(err).__name__}: {err}")
# TODO: print the cause
Hint 1

Write except ValueError as err: so you have a name for the original exception.

Hint 2

err.__cause__ is the original ValueError. Print type(cause).__name__ and cause.

Solution
class InvalidValueError(Exception):
"""A cell has a value, but the value breaks a rule."""
def parse_quantity(text, column="quantity"):
try:
return int(text)
except ValueError as err:
message = f"{column} {text!r} is not a whole number"
raise InvalidValueError(message) from err
print(parse_quantity("3"))
try:
parse_quantity("2.5")
except InvalidValueError as err:
print(f"{type(err).__name__}: {err}")
cause = err.__cause__
print(f"cause: {type(cause).__name__}: {cause}")
assert isinstance(cause, ValueError)
Output
3
InvalidValueError: quantity '2.5' is not a whole number
cause: ValueError: invalid literal for int() with base 10: '2.5'

How it works:

  1. int("2.5") raises ValueError; as err names it.
  2. raise InvalidValueError(message) from err creates the new error and stores err as its __cause__.
  3. The caller sees a message about the data (which column, which value) and can still reach the low-level details.
  4. isinstance(x, T) checks that a value is of type T or a subclass of it.

Alternative: from None would set __cause__ to None and hide the original error in tracebacks. Choose it only when the original adds nothing.

Core

Define ConfigError(Exception) with two subclasses, MissingKeyError and BadValueError. Write check_thresholds(config) for the thresholds section of data/config.json. It raises MissingKeyError when min_quantity, max_quantity or max_discount is missing, and BadValueError when min_quantity >= max_quantity or max_discount is not from 0 to 1. Test it on the real file and on two broken copies, catching ConfigError.

Expected output
config.json: ok
no_max: MissingKeyError: thresholds.max_quantity is missing
swapped: BadValueError: min_quantity (60) must be below max_quantity (50)
Starter
import copy
import json
# TODO: ConfigError, MissingKeyError, BadValueError
def check_thresholds(config):
# TODO: check the three keys, then the two rules
pass
with open("data/config.json", encoding="utf-8") as f:
config = json.load(f)
no_max = copy.deepcopy(config)
del no_max["thresholds"]["max_quantity"]
swapped = copy.deepcopy(config)
swapped["thresholds"]["min_quantity"] = 60
candidates = [("config.json", config), ("no_max", no_max), ("swapped", swapped)]
for name, candidate in candidates:
try:
check_thresholds(candidate)
except ConfigError as err:
print(f"{name}: {type(err).__name__}: {err}")
else:
print(f"{name}: ok")
Hint 1

json.load(f) turns the file into nested dicts. config["thresholds"] is the section to check.

Hint 2

Loop over the three required names and raise MissingKeyError for the first one that is not in the section.

Solution
import copy
import json
class ConfigError(Exception):
"""The pipeline config is unusable."""
class MissingKeyError(ConfigError):
"""A required key is missing."""
class BadValueError(ConfigError):
"""A key is present, but its value breaks a rule."""
def check_thresholds(config):
section = config["thresholds"]
for key in ("min_quantity", "max_quantity", "max_discount"):
if key not in section:
raise MissingKeyError(f"thresholds.{key} is missing")
if section["min_quantity"] >= section["max_quantity"]:
raise BadValueError(
f"min_quantity ({section['min_quantity']}) must be below "
f"max_quantity ({section['max_quantity']})"
)
if not 0 <= section["max_discount"] <= 1:
raise BadValueError(
f"max_discount must be from 0 to 1, got {section['max_discount']}"
)
with open("data/config.json", encoding="utf-8") as f:
config = json.load(f)
no_max = copy.deepcopy(config)
del no_max["thresholds"]["max_quantity"]
swapped = copy.deepcopy(config)
swapped["thresholds"]["min_quantity"] = 60
candidates = [("config.json", config), ("no_max", no_max), ("swapped", swapped)]
for name, candidate in candidates:
try:
check_thresholds(candidate)
except ConfigError as err:
print(f"{name}: {type(err).__name__}: {err}")
else:
print(f"{name}: ok")
assert issubclass(BadValueError, ConfigError)
Output
config.json: ok
no_max: MissingKeyError: thresholds.max_quantity is missing
swapped: BadValueError: min_quantity (60) must be below max_quantity (50)

How it works:

  1. One base class, ConfigError, groups both problems. The loop catches it, so it handles both.
  2. The real config has min_quantity 1, max_quantity 50 and max_discount 0.2, so it passes.
  3. copy.deepcopy() (module 04) makes independent copies, so deleting a key from no_max does not change config.
  4. The messages name the key with its section, thresholds.max_quantity, so the reader knows where to look.

Alternative: collect all problems in a list and raise one ConfigError that lists them, so a user fixes the whole file in one pass. Challenge M06-X03 does this with an exception group.

M06-C07 · Predict the output: finally and return

Section titled “M06-C07 · Predict the output: finally and return”
Core

Predict the output: load() opens a fake connection, and finally closes it. Write down what the three calls print. Pay attention to the order of the lines and to the call that fails with an exception that load() does not catch.

Acceptance criteria:

  • Write your prediction line by line, then run the code.
  • Your prediction matches the Output in the solution, including the line printed by the outer except.
Starter
def load(path):
print("open", path)
try:
if path.endswith(".json"):
raise TypeError("expected a CSV file")
if "missing" in path:
raise FileNotFoundError(path)
return "rows"
except FileNotFoundError:
print("not found")
return None
finally:
print("close", path)
for path in ["data/sales.csv", "data/missing.csv", "data/config.json"]:
try:
print("result:", load(path))
except TypeError as err:
print("caller got TypeError:", err)
# TODO: write your prediction before you run the code
Hint 1

print("result:", load(path)) must finish load() before it can print anything.

Hint 2

A TypeError is not caught inside load(), but finally still runs before the exception leaves the function.

Solution
def load(path):
print("open", path)
try:
if path.endswith(".json"):
raise TypeError("expected a CSV file")
if "missing" in path:
raise FileNotFoundError(path)
return "rows"
except FileNotFoundError:
print("not found")
return None
finally:
print("close", path)
for path in ["data/sales.csv", "data/missing.csv", "data/config.json"]:
try:
print("result:", load(path))
except TypeError as err:
print("caller got TypeError:", err)
assert load.__name__ == "load"
Output
open data/sales.csv
close data/sales.csv
result: rows
open data/missing.csv
not found
close data/missing.csv
result: None
open data/config.json
close data/config.json
caller got TypeError: expected a CSV file

How it works:

  1. data/sales.csv: return "rows" runs, then finally prints close, then the caller prints the result.
  2. data/missing.csv: FileNotFoundError is caught, the handler prints and returns None, finally prints close, then the caller prints result: None.
  3. data/config.json: the TypeError is not caught in load(). finally prints close first, then the exception reaches the caller’s except TypeError. No result: line appears for it.

Alternative: never put return inside finally. It replaces the function’s return value and swallows any exception that was on its way out. Python 3.14 warns about it.

Core

data/logs/app.log shows lines such as OperationalError: database is locked (attempt 1/3), retrying in 1s. Write retry(step, attempts, waits): it calls step(). When step() raises ConnectionError, it logs a warning with the attempt number and the wait from waits, then tries again. After the last attempt it re-raises. Do not really sleep. Test it with a fake step that fails twice, then with one that always fails.

Expected output
WARNING database is locked (attempt 1/3), retrying in 1s
WARNING database is locked (attempt 2/3), retrying in 2s
rows: 1200
WARNING database is unreachable (attempt 1/3), retrying in 1s
WARNING database is unreachable (attempt 2/3), retrying in 2s
ERROR database is unreachable (attempt 3/3), giving up
gave up: database is unreachable
Starter
import logging
import sys
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s",
stream=sys.stdout, force=True)
log = logging.getLogger("db")
def retry(step, attempts=3, waits=(1, 2, 4)):
# TODO: loop over the attempts; log and continue on ConnectionError;
# re-raise on the last attempt
pass
calls = {"count": 0}
def flaky_query():
calls["count"] += 1
if calls["count"] < 3:
raise ConnectionError("database is locked")
return 1200
def broken_query():
raise ConnectionError("database is unreachable")
print("rows:", retry(flaky_query))
try:
retry(broken_query)
except ConnectionError as err:
print("gave up:", err)
Hint 1

for attempt in range(1, attempts + 1): numbers the attempts from 1. return step() inside try ends the loop on success.

Hint 2

In the except ConnectionError as err: block: if attempt == attempts: raise. Otherwise log waits[attempt - 1].

Solution
import logging
import sys
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s",
stream=sys.stdout, force=True)
log = logging.getLogger("db")
def retry(step, attempts=3, waits=(1, 2, 4)):
for attempt in range(1, attempts + 1):
try:
return step()
except ConnectionError as err:
if attempt == attempts:
log.error("%s (attempt %d/%d), giving up", err, attempt, attempts)
raise
wait = waits[attempt - 1]
log.warning(
"%s (attempt %d/%d), retrying in %ds", err, attempt, attempts, wait
)
# time.sleep(wait) would pause here in a real pipeline
calls = {"count": 0}
def flaky_query():
calls["count"] += 1
if calls["count"] < 3:
raise ConnectionError("database is locked")
return 1200
def broken_query():
raise ConnectionError("database is unreachable")
print("rows:", retry(flaky_query))
try:
retry(broken_query)
except ConnectionError as err:
print("gave up:", err)
assert calls["count"] == 3
Output
WARNING database is locked (attempt 1/3), retrying in 1s
WARNING database is locked (attempt 2/3), retrying in 2s
rows: 1200
WARNING database is unreachable (attempt 1/3), retrying in 1s
WARNING database is unreachable (attempt 2/3), retrying in 2s
ERROR database is unreachable (attempt 3/3), giving up
gave up: database is unreachable

How it works:

  1. Each attempt calls step() inside try. On success, return leaves the loop and the function.
  2. On a ConnectionError, the handler logs the attempt and the wait, and the loop goes on.
  3. On the last attempt, the bare raise re-raises the same exception, so the caller sees the real error and can stop.
  4. The waits 1, 2, 4 are retry.backoff_seconds in data/config.json: each wait doubles. This is called exponential backoff.

Alternative: module 11 turns this function into a @retry decorator, so any function gets the behavior with one line.

Core

Choose a method and justify it: clean_quantities(rows) turns the quantity text of each row into an int. It has two checks: (a) each quantity is from 1 to 50 (max_quantity in data/config.json); (b) after cleaning, the number of clean rows plus rejected rows equals the number of input rows. Decide for each check whether it should be an assert or a raise, write the function and run it on the rows in the starter. Rejected rows are counted, not fatal.

Expected output
O002118: quantity 999 is outside 1-50
O007568: quantity -3 is outside 1-50
O013701: quantity 1000 is outside 1-50
1 clean, 3 rejected
Starter
def clean_quantities(rows):
clean, rejected = [], 0
for row in rows:
quantity = int(row["quantity"])
# TODO: check (a), with assert or raise; count rejected rows
clean.append({**row, "quantity": quantity})
# TODO: check (b), with assert or raise
return clean, rejected
rows = [ # lines 2, 153, 579 and 1109 of data/sales_raw.csv
{"order_id": "O000004", "product_id": "P002", "quantity": "1"},
{"order_id": "O002118", "product_id": "P030", "quantity": "999"},
{"order_id": "O007568", "product_id": "P013", "quantity": "-3"},
{"order_id": "O013701", "product_id": "P009", "quantity": "1000"},
]
clean, rejected = clean_quantities(rows)
print(f"{len(clean)} clean, {rejected} rejected")
Hint 1

Ask of each check: “Can this fail because of the data, or only because of a bug in my code?”

Hint 2

Which check could fail on a correct program with a bad file? Which one can fail only when the loop is wrong?

Solution
def check_quantity(quantity, low=1, high=50):
if not low <= quantity <= high:
raise ValueError(f"quantity {quantity} is outside {low}-{high}")
return quantity
def clean_quantities(rows):
clean, rejected = [], 0
for row in rows:
try:
quantity = check_quantity(int(row["quantity"]))
except ValueError as err:
print(f" {row['order_id']}: {err}")
rejected += 1
else:
clean.append({**row, "quantity": quantity})
assert len(clean) + rejected == len(rows), "lost a row while cleaning"
return clean, rejected
rows = [ # lines 2, 153, 579 and 1109 of data/sales_raw.csv
{"order_id": "O000004", "product_id": "P002", "quantity": "1"},
{"order_id": "O002118", "product_id": "P030", "quantity": "999"},
{"order_id": "O007568", "product_id": "P013", "quantity": "-3"},
{"order_id": "O013701", "product_id": "P009", "quantity": "1000"},
]
clean, rejected = clean_quantities(rows)
print(f"{len(clean)} clean, {rejected} rejected")
assert clean[0]["quantity"] == 1
Output
O002118: quantity 999 is outside 1-50
O007568: quantity -3 is outside 1-50
O013701: quantity 1000 is outside 1-50
1 clean, 3 rejected

How it works:

  1. Check (a) is a raise. Bad quantities come from the data: the file has 6 negative and 4 absurd ones. The check must run even under python -O, and the caller must be able to catch it, so check_quantity() raises ValueError.
  2. Check (b) is an assert. It can fail only if the loop itself is wrong, for example if someone deletes the rejected += 1 line. It documents an invariant and costs nothing.
  3. {**row, "quantity": quantity} copies the row dict and replaces one key (module 04).

Alternative: raise a custom InvalidValueError (as in the lesson’s Example 4) instead of ValueError, so the caller can tell a quantity problem from an int() failure.

M06-C10 · Interpret a log: warnings and errors by component

Section titled “M06-C10 · Interpret a log: warnings and errors by component”
Core

Interpret a result: count the WARNING and ERROR lines of data/logs/app.log per component (the word in square brackets). Print a small table, sorted by component. Then answer in one sentence each: which component has the most warnings, and which kind of error is the most frequent?

Expected output
component WARNING ERROR
api 13 3
db 0 2
loader 0 2
model 3 0
validator 9 0
Starter
counts = {} # component -> {"WARNING": n, "ERROR": n}
with open("data/logs/app.log", encoding="utf-8") as f:
for line in f.read().splitlines():
parts = line.split(" ", 4) # date, time, level, [component], message
# TODO: skip traceback lines; count WARNING and ERROR per component
pass
print(f"{'component':<10} {'WARNING':>7} {'ERROR':>5}")
# TODO: one line per component
Hint 1

A normal line has at least 5 parts, and its fourth part starts with [. Traceback lines do not.

Hint 2

parts[3].strip("[]") turns "[api]" into "api".

Solution
counts = {} # component -> {"WARNING": n, "ERROR": n}
with open("data/logs/app.log", encoding="utf-8") as f:
for line in f.read().splitlines():
parts = line.split(" ", 4) # date, time, level, [component], message
if len(parts) < 5 or not parts[3].startswith("["):
continue # a traceback line
level, component = parts[2], parts[3].strip("[]")
if level in ("WARNING", "ERROR"):
per_level = counts.setdefault(component, {"WARNING": 0, "ERROR": 0})
per_level[level] += 1
print(f"{'component':<10} {'WARNING':>7} {'ERROR':>5}")
for component in sorted(counts):
warnings, errors = counts[component]["WARNING"], counts[component]["ERROR"]
print(f"{component:<10} {warnings:>7} {errors:>5}")
assert sum(c["WARNING"] for c in counts.values()) == 25
assert sum(c["ERROR"] for c in counts.values()) == 7
Output
component WARNING ERROR
api 13 3
db 0 2
loader 0 2
model 3 0
validator 9 0

How it works:

  1. split(" ", 4) cuts at most 4 times, so the message stays in one piece.
  2. Traceback lines (8 in this file) have no [component] part and are skipped.
  3. The totals match the data dictionary: 25 warnings and 7 errors.

Interpretation: the api component has the most warnings: its 13 warnings are the 13 429 Too Many Requests responses, so clients hit the rate limit. The validator comes second with 9 warnings about missing customer_id values. The errors are spread over three components: 3 HTTP 500 responses in api, 2 locked-database errors in db that the pipeline retried, and 2 failed report parses in loader. No single kind of error dominates; the 500s are the most frequent.

Alternative: module 09 introduces collections.Counter, which counts (component, level) pairs in one line: Counter((c, lvl) for ...).

M06-C11 · Pull the tracebacks out of a log

Section titled “M06-C11 · Pull the tracebacks out of a log”
Core

data/logs/app.log contains two multi-line tracebacks under ERROR lines. Find every line that starts with Traceback, and print the time of the ERROR line just before it, the frame line and the last line of the traceback (the exception).

Expected output
10:53:56,110 File "pipeline/loader.py", line 58, in load_report
ValueError: Usecols do not match columns, columns expected but not found: ['quantity']
15:35:27,221 File "pipeline/loader.py", line 58, in load_report
ValueError: Usecols do not match columns, columns expected but not found: ['quantity']
Starter
with open("data/logs/app.log", encoding="utf-8") as f:
lines = f.read().splitlines()
for i, line in enumerate(lines):
if line.startswith("Traceback"):
# TODO: the ERROR line is lines[i - 1]; the traceback runs until the next
# line that starts with a date ("2024-")
pass
Hint 1

Use a while loop from i + 1 that stops at the first line starting with "2024-". The line before that stop is the exception line.

Hint 2

The time is lines[i - 1].split(" ")[1]. The frame line is the first line that starts with File.

Solution
with open("data/logs/app.log", encoding="utf-8") as f:
lines = f.read().splitlines()
found = 0
for i, line in enumerate(lines):
if line.startswith("Traceback"):
end = i + 1
while end < len(lines) and not lines[end].startswith("2024-"):
end += 1
block = lines[i:end]
time = lines[i - 1].split(" ")[1]
frame = next(row for row in block if row.startswith(" File"))
print(f"{time} {frame.strip()}")
print(f" {block[-1]}")
found += 1
assert found == 2
Output
10:53:56,110 File "pipeline/loader.py", line 58, in load_report
ValueError: Usecols do not match columns, columns expected but not found: ['quantity']
15:35:27,221 File "pipeline/loader.py", line 58, in load_report
ValueError: Usecols do not match columns, columns expected but not found: ['quantity']

How it works:

  1. The while loop walks forward until the next normal log line, which starts with a date.
  2. block[-1] is the last traceback line: the exception type and message, the line you read first.
  3. next(...) with a generator expression returns the first matching item (module 10 explains generators).
  4. Both tracebacks have the same cause: the loader expected a quantity column in data/reports/2024-04.csv.

Alternative: read the file line by line and keep a flag “inside a traceback”. That version also works on a log file too large to load at once (module 10).

Core

Fix the bug: this script recomputes the revenue of four lines of data/sales.csv and compares it with the stored revenue. Two lines do not match. Use the debugger to find the cause, then fix line_revenue(). The script is python/snippets/m06/revenue_check.py in the course repository; copy it into your project folder.

revenue_check.py
# revenue_check.py: recompute the revenue of four lines of data/sales.csv.
# Every line should match the revenue stored in the file. It has a bug.
lines = [
{
"order_id": "O000004",
"product_id": "P002",
"unit_price": 249.00,
"quantity": 1,
"discount": 0.1,
"revenue": 224.1,
},
{
"order_id": "O000005",
"product_id": "P022",
"unit_price": 29.99,
"quantity": 1,
"discount": 0.0,
"revenue": 29.99,
},
{
"order_id": "O000009",
"product_id": "P012",
"unit_price": 89.50,
"quantity": 2,
"discount": 0.0,
"revenue": 179.0,
},
{
"order_id": "O000051",
"product_id": "P001",
"unit_price": 79.99,
"quantity": 1,
"discount": 0.05,
"revenue": 75.99,
},
]
def line_revenue(line):
gross = line["unit_price"] * line["quantity"]
return round(gross * 1 - line["discount"], 2)
for line in lines:
expected = line["revenue"]
if line["order_id"] == "O000004":
breakpoint() # inspect the first line with a discount
got = line_revenue(line)
status = "ok" if got == expected else "MISMATCH"
print(f"{line['order_id']}: file {expected}, computed {got} {status}")
Expected output
O000004: file 224.1, computed 224.1 ok
O000005: file 29.99, computed 29.99 ok
O000009: file 179.0, computed 179.0 ok
O000051: file 75.99, computed 75.99 ok
Starter
def line_revenue(line):
gross = line["unit_price"] * line["quantity"]
return round(gross * 1 - line["discount"], 2) # TODO: fix the formula
Hint 1

Run python revenue_check.py. At the (Pdb) prompt, n moves to the line_revenue(line) call and s steps into it. p gross, line["discount"] shows the inputs.

Hint 2

This is the session with the commands n, s, n, n, two p commands and c. The stored revenue is 224.1. 249 minus 0.1 is 248.9. Which operation did Python do first?

Terminal
printf 'n\ns\nn\nn\np gross, line["discount"]\np gross * 1 - line["discount"]\nc\n' | python revenue_check.py
Output
> /path/to/my-course/revenue_check.py(47)<module>()
-> breakpoint() # inspect the first line with a discount
(Pdb) > /path/to/my-course/revenue_check.py(48)<module>()
-> got = line_revenue(line)
(Pdb) --Call--
> /path/to/my-course/revenue_check.py(39)line_revenue()
-> def line_revenue(line):
(Pdb) > /path/to/my-course/revenue_check.py(40)line_revenue()
-> gross = line["unit_price"] * line["quantity"]
(Pdb) > /path/to/my-course/revenue_check.py(41)line_revenue()
-> return round(gross * 1 - line["discount"], 2)
(Pdb) (249.0, 0.1)
(Pdb) 248.9
(Pdb) O000004: file 224.1, computed 248.9 MISMATCH
O000005: file 29.99, computed 29.99 ok
O000009: file 179.0, computed 179.0 ok
O000051: file 75.99, computed 79.94 MISMATCH
Solution
lines = [
{"order_id": "O000004", "product_id": "P002",
"unit_price": 249.00, "quantity": 1, "discount": 0.1, "revenue": 224.1},
{"order_id": "O000005", "product_id": "P022",
"unit_price": 29.99, "quantity": 1, "discount": 0.0, "revenue": 29.99},
{"order_id": "O000009", "product_id": "P012",
"unit_price": 89.50, "quantity": 2, "discount": 0.0, "revenue": 179.0},
{"order_id": "O000051", "product_id": "P001",
"unit_price": 79.99, "quantity": 1, "discount": 0.05, "revenue": 75.99},
]
def line_revenue(line):
gross = line["unit_price"] * line["quantity"]
return round(gross * (1 - line["discount"]), 2)
for line in lines:
expected = line["revenue"]
got = line_revenue(line)
status = "ok" if got == expected else "MISMATCH"
print(f"{line['order_id']}: file {expected}, computed {got} {status}")
assert all(line_revenue(line) == line["revenue"] for line in lines)
Output
O000004: file 224.1, computed 224.1 ok
O000005: file 29.99, computed 29.99 ok
O000009: file 179.0, computed 179.0 ok
O000051: file 75.99, computed 75.99 ok

How it works:

  1. The two failing lines are the two with a discount. That points at the discount part of the formula.
  2. In pdb, gross * 1 - line["discount"] is 248.9: Python multiplies first, then subtracts 0.1 from 249. At the same prompt, p gross * (1 - line["discount"]) gives 224.1, the stored revenue.
  3. The fix adds the parentheses and removes the breakpoint() line.

Alternative: without a debugger, print(f"{gross=} {line['discount']=}") inside line_revenue() shows the same inputs. pdb lets you try both formulas on the live values without editing and rerunning the script.

M06-C13 · Log a report to the terminal and a file

Section titled “M06-C13 · Log a report to the terminal and a file”
Core

Write a small report for data/reports/2024-01.csv. Create the logger report with two handlers: the terminal at INFO with the format %(levelname)s %(message)s, and the file output/report.log at DEBUG with the format %(levelname)s %(name)s %(message)s. Log one DEBUG line per category with its revenue, one INFO line with the total, and one WARNING for each row with a quantity of 4 or more (a bulk line). Then print the number of lines in the log file.

Expected output
WARNING bulk line O007114: 5 units of Trail Running Shoes
INFO total revenue 2024-01: 14162.33
8 lines in output/report.log
Starter
import csv
import logging
from pathlib import Path
Path("output").mkdir(exist_ok=True)
log = logging.getLogger("report")
log.setLevel(logging.DEBUG)
log.propagate = False
# TODO: a StreamHandler at INFO and a FileHandler at DEBUG, each with a Formatter
by_category = {}
with open("data/reports/2024-01.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
# TODO: add the revenue per category; warn for a quantity of 4 or more
pass
# TODO: log the categories (DEBUG) and the total (INFO); count the file lines
Hint 1

handler.setLevel(...) and handler.setFormatter(logging.Formatter("...")) configure one handler. log.addHandler(handler) attaches it.

Hint 2

Close the file handler with to_file.close() before you read the file back.

Solution
import csv
import logging
from pathlib import Path
Path("output").mkdir(exist_ok=True)
log = logging.getLogger("report")
log.setLevel(logging.DEBUG)
log.propagate = False
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
to_file = logging.FileHandler("output/report.log", mode="w", encoding="utf-8")
to_file.setLevel(logging.DEBUG)
to_file.setFormatter(logging.Formatter("%(levelname)s %(name)s %(message)s"))
log.addHandler(console)
log.addHandler(to_file)
by_category = {}
with open("data/reports/2024-01.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
category = row["category"]
by_category[category] = by_category.get(category, 0.0) + float(row["revenue"])
if int(row["quantity"]) >= 4:
log.warning("bulk line %s: %s units of %s", row["order_id"],
row["quantity"], row["product"])
for category in sorted(by_category):
log.debug("%s: %.2f", category, by_category[category])
log.info("total revenue 2024-01: %.2f", sum(by_category.values()))
to_file.close()
with open("output/report.log", encoding="utf-8") as f:
print(len(f.read().splitlines()), "lines in output/report.log")
assert round(sum(by_category.values()), 2) == 14162.33
Output
WARNING bulk line O007114: 5 units of Trail Running Shoes
INFO total revenue 2024-01: 14162.33
8 lines in output/report.log

How it works:

  1. The logger itself is at DEBUG, so every message reaches both handlers. Each handler then applies its own level.
  2. The terminal shows the WARNING and the INFO line. The file has them too, plus the six DEBUG lines, one per category: 8 lines.
  3. %.2f in the message formats the revenue with 2 decimals, like :.2f in an f-string.
  4. The total matches the data dictionary: 14,162.33 for January 2024.

Alternative: logging.config.dictConfig() builds the same setup from a dict, which you can load from a JSON or YAML file. Larger projects keep their logging setup in config this way.

M06-X01 · Collect every problem of every row

Section titled “M06-X01 · Collect every problem of every row”
Challenge

The lesson’s validator stops at the first problem of a row. Write row_problems(row, line_number) that checks all rules and returns a list of DataValidationError objects (an empty list for a clean row). Rules: customer_id, region, channel, discount and unit_price must not be a missing token ("", "N/A", "-"); quantity must be from 1 to 50. Run it on data/sales_raw.csv and print the number of problems per column and the number of rows with at least one problem. The counts per column must equal the data dictionary.

Expected output
customer_id 23
region 17
channel 17
discount 24
unit_price 10
quantity 10
99 of 1200 rows have at least one problem
101 problems in total
Starter
import csv
MISSING_TOKENS = {"", "N/A", "-"}
REQUIRED = ["customer_id", "region", "channel", "discount", "unit_price"]
class DataValidationError(Exception):
def __init__(self, message, *, column=None, line_number=None):
super().__init__(message)
self.column = column
self.line_number = line_number
class MissingValueError(DataValidationError):
"""A required cell is empty or holds a missing-value token."""
class InvalidValueError(DataValidationError):
"""A cell has a value, but the value breaks a rule."""
def row_problems(row, line_number):
problems = []
# TODO: one MissingValueError per missing required cell
# TODO: one InvalidValueError for a quantity outside 1-50
return problems
# TODO: run row_problems on every row; count by column and count bad rows
Hint 1

You do not need to raise an exception to use it. MissingValueError("...", column=c) creates the object; problems.append(...) stores it.

Hint 2

Count with by_column[err.column] = by_column.get(err.column, 0) + 1 for each err in the returned list.

Hint 3

The data dictionary lists: customer_id 23, region 17, channel 17, discount 24, unit_price 10, and 10 bad quantities (6 negative, 4 absurd).

Solution
import csv
MISSING_TOKENS = {"", "N/A", "-"}
REQUIRED = ["customer_id", "region", "channel", "discount", "unit_price"]
class DataValidationError(Exception):
def __init__(self, message, *, column=None, line_number=None):
super().__init__(message)
self.column = column
self.line_number = line_number
class MissingValueError(DataValidationError):
"""A required cell is empty or holds a missing-value token."""
class InvalidValueError(DataValidationError):
"""A cell has a value, but the value breaks a rule."""
def row_problems(row, line_number):
problems = []
for column in REQUIRED:
if row[column].strip() in MISSING_TOKENS:
problems.append(MissingValueError(
f"line {line_number}: {column} is missing",
column=column, line_number=line_number,
))
quantity = int(row["quantity"])
if not 1 <= quantity <= 50:
problems.append(InvalidValueError(
f"line {line_number}: quantity {quantity} is outside 1-50",
column="quantity", line_number=line_number,
))
return problems
by_column, bad_rows, total_rows = {}, 0, 0
with open("data/sales_raw.csv", encoding="utf-8", newline="") as f:
for line_number, row in enumerate(csv.DictReader(f), start=2):
total_rows += 1
problems = row_problems(row, line_number)
if problems:
bad_rows += 1
for err in problems:
by_column[err.column] = by_column.get(err.column, 0) + 1
for column in [*REQUIRED, "quantity"]:
print(f"{column:<12} {by_column.get(column, 0):>3}")
print(f"{bad_rows} of {total_rows} rows have at least one problem")
print(f"{sum(by_column.values())} problems in total")
assert by_column == {"customer_id": 23, "region": 17, "channel": 17,
"discount": 24, "unit_price": 10, "quantity": 10}
Output
customer_id 23
region 17
channel 17
discount 24
unit_price 10
quantity 10
99 of 1200 rows have at least one problem
101 problems in total

How it works:

  1. Exceptions are ordinary objects. row_problems() creates them without raising, so it can check every rule of a row.
  2. Each object keeps its column, so counting by column needs no message parsing.
  3. All six counts equal the data dictionary. The number of problems is larger than the number of bad rows, because two rows break two rules each (101 problems in 99 rows).

Alternative: raise the list as one exception group, so a caller that wants to stop at a bad row still can. Challenge M06-X03 does this.

M06-X02 · A config loader with clear, chained errors

Section titled “M06-X02 · A config loader with clear, chained errors”
Challenge

Write load_config(path). It reads a JSON config and returns the dict. Translate every low-level failure into a ConfigError chained with from: a missing file (FileNotFoundError), invalid JSON (json.JSONDecodeError) and a missing top-level key from REQUIRED_KEYS (KeyError). The message must name the file. Test it on data/config.json, on data/settings.json (it does not exist) and on a broken file that you write to output/broken.json.

Expected output
data/config.json: ok, project 'sales-pipeline'
data/settings.json: config file data/settings.json does not exist
cause: FileNotFoundError
output/broken.json: output/broken.json is not valid JSON (line 1, column 20)
cause: JSONDecodeError
output/no_model.json: output/no_model.json has no 'model' section
Starter
import json
from pathlib import Path
REQUIRED_KEYS = ("input", "output", "thresholds", "model")
class ConfigError(Exception):
"""The config file cannot be used."""
def load_config(path):
# TODO: open and parse the file; check REQUIRED_KEYS;
# raise ConfigError(...) from err for each low-level error
pass
Path("output").mkdir(exist_ok=True)
Path("output/broken.json").write_text('{"project": "sales",}', encoding="utf-8")
for path in ["data/config.json", "data/settings.json", "output/broken.json"]:
try:
config = load_config(path)
except ConfigError as err:
print(f"{path}: {err}")
print(f" cause: {type(err.__cause__).__name__}")
else:
print(f"{path}: ok, project {config['project']!r}")
Hint 1

Use one try block for open() and json.load(), with two except clauses. json.JSONDecodeError has the attributes lineno and colno.

Hint 2

For the keys, build {key: config[key] for key in REQUIRED_KEYS} inside a try block. A missing key raises KeyError, and err.args[0] is that key.

Solution
import json
from pathlib import Path
REQUIRED_KEYS = ("input", "output", "thresholds", "model")
class ConfigError(Exception):
"""The config file cannot be used."""
def load_config(path):
try:
with open(path, encoding="utf-8") as f:
config = json.load(f)
except FileNotFoundError as err:
raise ConfigError(f"config file {path} does not exist") from err
except json.JSONDecodeError as err:
message = f"{path} is not valid JSON (line {err.lineno}, column {err.colno})"
raise ConfigError(message) from err
try:
sections = {key: config[key] for key in REQUIRED_KEYS}
except KeyError as err:
raise ConfigError(f"{path} has no {err.args[0]!r} section") from err
return {**config, **sections}
Path("output").mkdir(exist_ok=True)
Path("output/broken.json").write_text('{"project": "sales",}', encoding="utf-8")
for path in ["data/config.json", "data/settings.json", "output/broken.json"]:
try:
config = load_config(path)
except ConfigError as err:
print(f"{path}: {err}")
print(f" cause: {type(err.__cause__).__name__}")
else:
print(f"{path}: ok, project {config['project']!r}")
Path("output/no_model.json").write_text('{"input": {}, "output": {}, "thresholds": {}}',
encoding="utf-8")
try:
load_config("output/no_model.json")
except ConfigError as err:
print(f"output/no_model.json: {err}")
assert isinstance(err.__cause__, KeyError)
Output
data/config.json: ok, project 'sales-pipeline'
data/settings.json: config file data/settings.json does not exist
cause: FileNotFoundError
output/broken.json: output/broken.json is not valid JSON (line 1, column 20)
cause: JSONDecodeError
output/no_model.json: output/no_model.json has no 'model' section

How it works:

  1. Each low-level error has its own except clause, so each gets its own clear message.
  2. from err keeps the original in __cause__. A developer still sees the JSON position or the OS error in the traceback.
  3. The broken file has a trailing comma, which JSON does not allow. JSONDecodeError reports the exact line and column.
  4. The caller handles one type, ConfigError, whatever went wrong inside.

Alternative: if key not in config: raise ConfigError(...) is simpler for the keys (LBYL). The try version is shown because it chains the KeyError; both are fine here.

M06-X03 · Report all problems at once with an exception group

Section titled “M06-X03 · Report all problems at once with an exception group”
Challenge

An exception group (ExceptionGroup, Python 3.11+) carries several exceptions at once, and groups can be nested. An except* T clause takes the errors of type T out of a group, at any depth. Write validate_file(path) for data/sales_raw.csv:

  • If the header lacks a column of REQUIRED, raise at once ExceptionGroup(f"{path}: validation failed", [MissingColumnError(...)]).
  • Otherwise check every row: a missing token in customer_id, region, channel, discount or unit_price is a MissingValueError; a quantity outside 1-50 is an InvalidValueError. Collect the errors of one row in ExceptionGroup(f"line {n}", row_errors), and raise one file-level group of all row groups.

Then write report(path), which handles MissingValueError and InvalidValueError with two except* clauses and counts the errors per column. It does not handle MissingColumnError. Run it on data/sales_raw.csv and check the counts against the data dictionary. Then run it on data/reports/2024-01.csv and show that the unhandled error reaches the caller.

Expected output
rows with an invalid value: 10
customer_id 23
region 17
channel 17
discount 24
unit_price 10
quantity 10
reached the caller: ['MissingColumnError']
missing columns ['customer_id', 'region', 'channel', 'discount', 'unit_price']
Starter
import csv
MISSING_TOKENS = {"", "N/A", "-"}
REQUIRED = ["customer_id", "region", "channel", "discount", "unit_price", "quantity"]
class DataValidationError(Exception):
def __init__(self, message, *, column=None):
super().__init__(message)
self.column = column
class MissingColumnError(DataValidationError):
"""A required column is not in the header."""
class MissingValueError(DataValidationError):
"""A required cell is empty or holds a missing-value token."""
class InvalidValueError(DataValidationError):
"""A cell has a value, but the value breaks a rule."""
def leaves(group):
"""Yield the plain exceptions inside a (nested) exception group."""
for err in group.exceptions:
if isinstance(err, BaseExceptionGroup):
yield from leaves(err)
else:
yield err
def validate_file(path):
# TODO: header check; one ExceptionGroup per bad row; one group for the file
pass
def report(path):
counts = {}
# TODO: try validate_file(path); except* MissingValueError; except* InvalidValueError
return counts
Hint 1

raise ExceptionGroup("message", [err1, err2]) needs a non-empty list. Only build a row group when the row has errors.

Hint 2

Inside except* MissingValueError as group:, group keeps the nesting: file group, then row groups, then the errors. leaves(group) walks down to the errors, so you can read err.column.

Hint 3

For the second file, wrap report(...) in try/except* MissingColumnError as group: at the caller, and print the type names of group.exceptions.

Solution
import csv
MISSING_TOKENS = {"", "N/A", "-"}
REQUIRED = ["customer_id", "region", "channel", "discount", "unit_price", "quantity"]
class DataValidationError(Exception):
def __init__(self, message, *, column=None):
super().__init__(message)
self.column = column
class MissingColumnError(DataValidationError):
"""A required column is not in the header."""
class MissingValueError(DataValidationError):
"""A required cell is empty or holds a missing-value token."""
class InvalidValueError(DataValidationError):
"""A cell has a value, but the value breaks a rule."""
def leaves(group):
"""Yield the plain exceptions inside a (nested) exception group."""
for err in group.exceptions:
if isinstance(err, BaseExceptionGroup):
yield from leaves(err)
else:
yield err
def row_errors(row, n):
errors = []
for column in REQUIRED[:-1]:
if row[column].strip() in MISSING_TOKENS:
errors.append(MissingValueError(f"line {n}: {column}", column=column))
if not 1 <= int(row["quantity"]) <= 50:
message = f"line {n}: quantity {row['quantity']}"
errors.append(InvalidValueError(message, column="quantity"))
return errors
def validate_file(path):
title = f"{path}: validation failed"
with open(path, encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
missing = [c for c in REQUIRED if c not in reader.fieldnames]
if missing:
error = MissingColumnError(f"missing columns {missing}", column=missing[0])
raise ExceptionGroup(title, [error])
row_groups = []
for n, row in enumerate(reader, start=2):
errors = row_errors(row, n)
if errors:
row_groups.append(ExceptionGroup(f"line {n}", errors))
if row_groups:
raise ExceptionGroup(title, row_groups)
def count_by_column(group, counts):
for err in leaves(group):
counts[err.column] = counts.get(err.column, 0) + 1
def report(path):
counts = {}
try:
validate_file(path)
except* MissingValueError as group:
count_by_column(group, counts)
except* InvalidValueError as group:
count_by_column(group, counts)
print("rows with an invalid value:", len(group.exceptions))
return counts
counts = report("data/sales_raw.csv")
for column in REQUIRED:
print(f"{column:<12} {counts.get(column, 0):>3}")
assert counts == {"customer_id": 23, "region": 17, "channel": 17,
"discount": 24, "unit_price": 10, "quantity": 10}
try:
report("data/reports/2024-01.csv")
except* MissingColumnError as group:
print("reached the caller:", [type(e).__name__ for e in group.exceptions])
print(" ", group.exceptions[0])
Output
rows with an invalid value: 10
customer_id 23
region 17
channel 17
discount 24
unit_price 10
quantity 10
reached the caller: ['MissingColumnError']
missing columns ['customer_id', 'region', 'channel', 'discount', 'unit_price']

How it works:

  1. validate_file() does not stop at the first bad row. Each bad row becomes a small group, and the file becomes one group of 99 row groups.
  2. except* matches errors inside the groups, at any depth. The first clause takes all MissingValueErrors, the second all InvalidValueErrors. Each clause gets a copy of the file group that holds only the matching errors, with the same nesting. In the second clause, group.exceptions is the list of the 10 row groups with a bad quantity.
  3. Both clauses run for the same file, because the group holds both types.
  4. For the monthly report, no except* clause in report() matches MissingColumnError. It travels up, still inside a group, to the caller’s except* MissingColumnError. Nothing is lost silently.
  5. Libraries use exception groups when several tasks fail at once, for example concurrent downloads (module 15).

Alternative: return a list of errors, as in M06-X01. Use a group when the default must be “stop”, but a caller may want to handle each kind of problem in its own clause.

M06-X04 · A pipeline runner with logging and cleanup

Section titled “M06-X04 · A pipeline runner with logging and cleanup”
Challenge

Write run_pipeline(run_id, steps). steps is a list of (name, function) pairs. The runner logs Starting pipeline <run_id>, runs each step and logs step <name> ok. A DataValidationError in a step is expected: log it as an ERROR, stop running steps and set the status to failed. Any other exception is a bug: log it with its traceback and re-raise it. In every case, log Finished <run_id> status=<status> in a finally block, the way data/logs/app.log does. Return the status. Test three runs: all steps pass, a validation step fails, a step has a bug.

Expected output
INFO [pipeline] Starting pipeline run-0001
INFO [pipeline] step load ok
INFO [pipeline] step validate ok
INFO [pipeline] Finished run-0001 status=success
success
INFO [pipeline] Starting pipeline run-0002
INFO [pipeline] step load ok
ERROR [pipeline] step validate failed validation: 23 rows with missing customer_id
INFO [pipeline] Finished run-0002 status=failed
failed
INFO [pipeline] Starting pipeline run-0003
INFO [pipeline] step load ok
ERROR [pipeline] step export crashed: ZeroDivisionError
Traceback (most recent call last):
File "/path/to/my-course/pipeline_runner.py", line 21, in run_pipeline
step()
~~~~^^
File "/path/to/my-course/pipeline_runner.py", line 49, in export_bug
return 1200 / 0 # a bug
~~~~~^~~
ZeroDivisionError: division by zero
INFO [pipeline] Finished run-0003 status=crashed
the bug reached the caller
Starter
import logging
import sys
# stdout, so the log lines and the printed statuses come out in one ordered stream
logging.basicConfig(level=logging.INFO, format="%(levelname)s [%(name)s] %(message)s",
stream=sys.stdout, force=True)
log = logging.getLogger("pipeline")
class DataValidationError(Exception):
"""A value in the input data breaks a rule."""
def run_pipeline(run_id, steps):
status = "running"
log.info("Starting pipeline %s", run_id)
# TODO: try / except DataValidationError / except Exception / finally
return status
def load():
return 1200
def validate_ok():
return 0
def validate_bad():
raise DataValidationError("23 rows with missing customer_id")
def export_bug():
return 1200 / 0 # a bug
first = run_pipeline("run-0001", [("load", load), ("validate", validate_ok)])
print(first)
second = run_pipeline("run-0002", [("load", load), ("validate", validate_bad),
("export", export_bug)])
print(second)
try:
run_pipeline("run-0003", [("load", load), ("export", export_bug)])
except ZeroDivisionError:
print("the bug reached the caller")
Hint 1

Put the whole loop over the steps in one try block. A return inside finally would swallow the re-raised bug, so return after the statement.

Hint 2

Set status = "success" after the loop, status = "failed" in the DataValidationError handler, and status = "crashed" before the bare raise.

Solution
pipeline_runner.py
"""pipeline_runner.py: run pipeline steps with logging and cleanup."""
import logging
import sys
# stdout, so the log lines and the printed statuses come out in one ordered stream
logging.basicConfig(level=logging.INFO, format="%(levelname)s [%(name)s] %(message)s",
stream=sys.stdout, force=True)
log = logging.getLogger("pipeline")
class DataValidationError(Exception):
"""A value in the input data breaks a rule."""
def run_pipeline(run_id, steps):
status = "running"
log.info("Starting pipeline %s", run_id)
try:
for name, step in steps:
step()
log.info("step %s ok", name)
status = "success"
except DataValidationError as err:
log.error("step %s failed validation: %s", name, err)
status = "failed"
except Exception as err:
log.exception("step %s crashed: %s", name, type(err).__name__)
status = "crashed"
raise
finally:
log.info("Finished %s status=%s", run_id, status)
return status
def load():
return 1200
def validate_ok():
return 0
def validate_bad():
raise DataValidationError("23 rows with missing customer_id")
def export_bug():
return 1200 / 0 # a bug
first = run_pipeline("run-0001", [("load", load), ("validate", validate_ok)])
print(first)
second = run_pipeline("run-0002", [("load", load), ("validate", validate_bad),
("export", export_bug)])
print(second)
try:
run_pipeline("run-0003", [("load", load), ("export", export_bug)])
except ZeroDivisionError:
print("the bug reached the caller")
assert (first, second) == ("success", "failed")
Output
INFO [pipeline] Starting pipeline run-0001
INFO [pipeline] step load ok
INFO [pipeline] step validate ok
INFO [pipeline] Finished run-0001 status=success
success
INFO [pipeline] Starting pipeline run-0002
INFO [pipeline] step load ok
ERROR [pipeline] step validate failed validation: 23 rows with missing customer_id
INFO [pipeline] Finished run-0002 status=failed
failed
INFO [pipeline] Starting pipeline run-0003
INFO [pipeline] step load ok
ERROR [pipeline] step export crashed: ZeroDivisionError
Traceback (most recent call last):
File "/path/to/my-course/pipeline_runner.py", line 21, in run_pipeline
step()
~~~~^^
File "/path/to/my-course/pipeline_runner.py", line 49, in export_bug
return 1200 / 0 # a bug
~~~~~^~~
ZeroDivisionError: division by zero
INFO [pipeline] Finished run-0003 status=crashed
the bug reached the caller

How it works:

  1. Run 1: both steps pass, status becomes success, finally logs the end, the function returns.
  2. Run 2: validate_bad() raises a DataValidationError. The handler logs it and sets failed. The export step never runs.
  3. Run 3: the ZeroDivisionError is a bug. The handler logs it, sets crashed and re-raises. finally still logs the end line before the exception reaches the caller.
  4. name is still bound in the handlers: it is the step that was running when the exception happened.
  5. The second handler uses log.exception(...), so the log keeps the full traceback of the bug, with the file and line. A validation failure is expected, so log.error() without a traceback is enough there.

Alternative: let each step return a status instead of raising. That spreads if status != "ok" checks everywhere; exceptions keep the happy path clean and the error handling in one place.

M06-X05 · Debug a churn rate that is too good to be true

Section titled “M06-X05 · Debug a churn rate that is too good to be true”
Challenge

Interpret and fix: the script below computes the churn rate and the mean total_charges of data/customers.csv. It prints a churn rate of 100%, and it crashes on total_charges. The data dictionary says that the churn rate is 19.26% and that 10 new customers have a blank total_charges. Find both bugs and fix them. Skip and count the blank charges. Then add data checks that would catch bug 1 next time: raise a ValueError when churned holds anything but "0" and "1", or when the rate is not plausible (not between 0 and 50%). End with an assert for an invariant of your own code.

import csv
with open("data/customers.csv", encoding="utf-8", newline="") as f:
customers = list(csv.DictReader(f))
churned = sum(1 for c in customers if c["churned"])
print(f"churn rate: {churned / len(customers):.2%}")
charges = [float(c["total_charges"]) for c in customers]
print(f"mean total_charges: {sum(charges) / len(charges):.2f}")
Output
churn rate: 100.00%
ValueError: could not convert string to float: ''
Expected output
first churned value: '0'
churn rate: 19.26%
mean total_charges: 1385.69 (10 blank: C04991..C05000)
Starter
import csv
with open("data/customers.csv", encoding="utf-8", newline="") as f:
customers = list(csv.DictReader(f))
churned = sum(1 for c in customers if c["churned"]) # TODO: bug 1
print(f"churn rate: {churned / len(customers):.2%}")
charges = [float(c["total_charges"]) for c in customers] # TODO: bug 2
print(f"mean total_charges: {sum(charges) / len(charges):.2f}")
# TODO: raise ValueError for bad data; assert an invariant of the code
Hint 1

Print repr(customers[0]["churned"]). What type is it, and is it truthy?

Hint 2

bool("0") is True: every non-empty string is truthy. Convert with int() first.

Hint 3

The traceback ends with could not convert string to float: ''. Use a loop with try/except ValueError around float() and count the skips.

Solution
import csv
with open("data/customers.csv", encoding="utf-8", newline="") as f:
customers = list(csv.DictReader(f))
print("first churned value:", repr(customers[0]["churned"]))
churned = sum(int(c["churned"]) for c in customers)
rate = churned / len(customers)
print(f"churn rate: {rate:.2%}")
charges, blank_ids = [], []
for c in customers:
try:
charges.append(float(c["total_charges"]))
except ValueError:
blank_ids.append(c["customer_id"])
print(f"mean total_charges: {sum(charges) / len(charges):.2f} "
f"({len(blank_ids)} blank: {blank_ids[0]}..{blank_ids[-1]})")
values = {c["churned"] for c in customers}
if values != {"0", "1"}:
raise ValueError(f"churned must hold '0' and '1', got {sorted(values)}")
if not 0 < rate < 0.5:
raise ValueError(f"churn rate {rate:.2%} is not plausible")
assert len(charges) + len(blank_ids) == len(customers), "lost a customer"
Output
first churned value: '0'
churn rate: 19.26%
mean total_charges: 1385.69 (10 blank: C04991..C05000)

How it works:

  1. Bug 1. csv gives every value as text. "0" is a non-empty string, so it is truthy, and the generator counts every customer: 100%. int(c["churned"]) turns "0" and "1" into numbers, and sum() counts the 1s.
  2. Bug 2. The 10 customers with tenure 0 have an empty total_charges. float("") raises ValueError. The loop catches it and records the id.
  3. The blank ids are C04991 to C05000, the 10 newest customers, as the data dictionary says.
  4. Guards. The two checks test the data, so they raise ValueError: they must also run in a pipeline started with python -O. The first checks that the column holds only "0" and "1". The second checks that the rate is plausible: no real business has 100% churn. Bug 1 had no traceback at all; only a sanity check like this catches it. The final assert tests the code: every customer is either charged or counted as blank. In a one-off analysis script, quick asserts on the data are acceptable; in a pipeline that runs unattended, raise.

Alternative: pandas (module 24) reads churned as integers and the blank charges as NaN, so df["churned"].mean() and df["total_charges"].mean() give both answers. Knowing why the plain version failed helps you check pandas’ choices too.