Objectives: LO-12.1, LO-12.2, LO-12.3, LO-12.4
Prerequisites: the Module 12 reading and
Lab 11
Time: about 2 hours
In this lab you read a traceback from a script, predict which exception each of eight lines
raises, write an input loop and a file reader that recover from bad input, raise errors with
clear messages, and then find and fix three planted bugs with the method from the reading.
Each exercise ends with a check cell that prints passed or says what is wrong.
Setup¶
Run the next cell first. It writes a script, stations.py, and a CSV file into
scratch/lab12, and defines two helpers:
run_script(name)runs a script in that folder with Python, as a terminal would, and prints what it printed and its exit status.typed(...)makes a stand-in forinputthat “types” the answers you give it, one for each call, and then raisesEOFError, asinputdoes when the input ends. The checks use it to test functions that ask for input, without a keyboard.
import contextlib
import csv
import io
import math
import os
import subprocess
import sys
from pathlib import Path
print("Python", sys.version.split()[0])
LAB = Path("scratch") / "lab12"
LAB.mkdir(parents=True, exist_ok=True)
STATIONS = '''"""Print the mean temperature of each station."""
def parse(line):
station, date, text = line.split(",")
return station, float(text)
def summarize(lines):
totals = {}
counts = {}
for line in lines:
station, temperature = parse(line)
totals[station] = totals.get(station, 0) + temperature
counts[station] = counts.get(station, 0) + 1
means = {}
for station in totals:
means[station] = totals[station] / counts[station]
return means
def main():
lines = ["Harbor,2026-11-02,8.5", "Hilltop,2026-11-02,n/a", "Harbor,2026-11-03,11.0"]
means = summarize(lines)
for station in means:
print(f"{station}: {means[station]:.1f}")
main()
'''
(LAB / "stations.py").write_text(STATIONS, encoding="utf-8")
(LAB / "readings.csv").write_text(
"station,date,temp_c\n"
"Harbor,2026-11-02,8.5\n"
"Hilltop,2026-11-02,n/a\n"
"Harbor,2026-11-03,11.0\n"
"Hilltop,2026-11-03,\n"
"Harbor,2026-11-04,6.5\n"
"Hilltop,2026-11-04,warm\n",
encoding="utf-8",
)
def run_script(name):
"""Run the script name in LAB with Python, and print its output and exit status."""
result = subprocess.run(
[sys.executable, name], cwd=LAB, capture_output=True, text=True,
env={**os.environ, "PYTHON_COLORS": "0"},
)
print(result.stdout + result.stderr, end="")
print(f"(exit status {result.returncode})")
def typed(*answers):
"""Return a stand-in for input that types each answer in turn, then ends the input."""
remaining = list(answers)
ended = []
def read(prompt=""):
print(prompt, end="")
if remaining:
answer = remaining.pop(0)
print(answer)
return answer
if not ended:
ended.append(True)
print()
raise EOFError("EOF when reading a line")
print("1")
return "1"
return read
print("Ready.")1. Reading a traceback¶
Run the next cell. It runs stations.py, which stops with a traceback.
run_script("stations.py")Exercise L12.1 (LO-12.1, ★, about 10 minutes)¶
From the traceback above, give:
t1: the exception’s name, as a string.t2: the function that raised it, andt3: the line number of the line that raised it.t4: the chain of calls, as a list of names from the first frame to the last, starting with"<module>".t5: the value in the data that caused it, as a string.
t1 = "..."
t2 = "..."
t3 = 0
t4 = []
t5 = "..."assert t1 == "ValueError", "t1: the exception's name is on the last line, before the colon."
assert t2 == "parse", "t2: the last frame names the function that raised the exception."
assert t3 == 6, "t3: the last frame's File line gives the line number."
assert t4 == ["<module>", "main", "summarize", "parse"], (
"t4: read the function names on the File lines, from the top down."
)
assert t5 == "n/a", "t5: the message quotes the text float couldn't convert."
print("passed")2. Which exception?¶
Exercise L12.2 (LO-12.1, ★, about 10 minutes)¶
Each of these eight expressions raises an exception. Without running them, give the name of
each one’s exception as a string, in e1 to e8: for example, e1 = "TypeError".
| Expression | |
|---|---|
e1 | int("3.5") |
e2 | ["a", "b"][2] |
e3 | {"Harbor": 8.5}["harbor"] |
e4 | "8.5" * 2.0 |
e5 | (8.5).append(1) |
e6 | open("no-such-file.csv") |
e7 | math.sqrt(-1) |
e8 | total_rainfall + 1, where nothing has set total_rainfall |
The check runs each expression and compares its exception with your answer, one at a time.
e1 = "..."
e2 = "..."
e3 = "..."
e4 = "..."
e5 = "..."
e6 = "..."
e7 = "..."
e8 = "..."EXPRESSIONS = ['int("3.5")', '["a", "b"][2]', '{"Harbor": 8.5}["harbor"]', '"8.5" * 2.0',
"(8.5).append(1)", 'open("no-such-file.csv")', "math.sqrt(-1)",
"total_rainfall + 1"]
answers = [e1, e2, e3, e4, e5, e6, e7, e8]
for number, (expression, answer) in enumerate(zip(EXPRESSIONS, answers), start=1):
try:
eval(expression)
except Exception as error:
actual = type(error).__name__
message = str(error)
assert answer == actual, f"e{number}: {expression} raises {actual}: {message}"
print("passed")3. Recovering from bad input¶
Exercise L12.3 (LO-12.2, ★★, about 20 minutes)¶
Write ask_number(prompt, low, high, read=input), which asks for a whole number from low to
high until it gets one, and returns it as an int. read is the function that reads each
line: input, unless a caller passes another, as the check does with typed.
Convert the text with
intin atrystatement. For text that isn’t a whole number, print a message that shows the text with its quotes, using{text!r}, and ask again.For a number outside the range, print a message that names the range, such as
Type a number from 1 to 31., and ask again.Catch only
ValueError. When the input ends,readraisesEOFError, andask_numbermust let it go on to its caller, so that a program can stop politely, asconvert.pydoes in the reading. The check also passesNoneas an answer, which makesintraiseTypeError: a bug, whichask_numbermust let through too.
Hint
Follow the reading’s ask_number, with int in place of float, and read(prompt) in place of input(prompt). Check the range in the else clause, or after the try statement.
def ask_number(prompt, low, high, read=input):
"""Ask until the user types a whole number from low to high, and return it."""
...output = io.StringIO()
with contextlib.redirect_stdout(output):
day = ask_number("Day: ", 1, 31, read=typed("", "ten", "2.5", "0", "32", " 31 "))
shown = output.getvalue()
print(shown)
assert day == 31 and isinstance(day, int), f"ask_number returned {day!r}, not 31."
assert shown.count("Day: ") == 6, "Ask again after each bad answer, with the same prompt."
assert "'ten'" in shown and "''" in shown, "Show the text that isn't a number, with {text!r}."
assert "1 to 31" in shown, "Name the range when a number is outside it."
ended = False
try:
with contextlib.redirect_stdout(io.StringIO()):
ask_number("Day: ", 1, 31, read=typed("x"))
except EOFError:
ended = True
assert ended, "When the input ends, let EOFError through: catch only ValueError."
raised = None
try:
with contextlib.redirect_stdout(io.StringIO()):
ask_number("Day: ", 1, 31, read=typed(None))
except (TypeError, EOFError) as error:
raised = type(error).__name__
assert raised == "TypeError", (
"Catch only ValueError: int(None) raises TypeError, a sign of a bug, "
"which ask_number should let through instead of reporting it as bad input."
)
print("passed")4. else and finally¶
Exercise L12.4 (LO-12.2, ★, about 10 minutes)¶
Read this function, and without running it, give:
p1: the letters thatdescribe("4")prints, in order, as a list of strings.p2: the letters thatdescribe("x")prints, andp3: whatdescribe("x")returns.
def describe(text):
try:
number = int(text)
except ValueError:
print("A")
return "not a number"
else:
print("B")
finally:
print("C")
print("D")
return number * 2p1 = []
p2 = []
p3 = Nonedef describe(text):
try:
number = int(text)
except ValueError:
print("A")
return "not a number"
else:
print("B")
finally:
print("C")
print("D")
return number * 2
for text, letters in [("4", p1), ("x", p2)]:
output = io.StringIO()
with contextlib.redirect_stdout(output):
result = describe(text)
printed = output.getvalue().split()
assert letters == printed, f'describe("{text}") prints {printed}.'
assert p3 == "not a number", "p3: finally runs, and then the except clause's return finishes."
print("passed")5. Skipping bad rows¶
Run the next cell to see readings.csv, which the setup cell wrote. Three of its rows have a
temperature that isn’t a number.
for number, line in enumerate((LAB / "readings.csv").read_text(encoding="utf-8").splitlines(),
start=1):
print(number, line)Exercise L12.5 (LO-12.2, ★★, about 15 minutes)¶
Write read_temperatures(path), which reads a CSV file with the columns station, date, and
temp_c, and returns two lists: a (station, temperature) tuple for each row whose temp_c is
a number, with the temperature as a float, and the line number of each row whose temp_c
isn’t. The header is line 1, so the first row is line 2.
Convert
temp_cin atrystatement, catchValueError, and add the good row in theelseclause.Don’t catch
FileNotFoundError:read_temperaturescan’t do anything useful about a missing file, so its caller should hear about it.
Hint
enumerate(csv.DictReader(file), start=2) numbers the rows from 2. Return the two lists as a tuple: return readings, bad_lines.
def read_temperatures(path):
"""Return the good (station, temperature) rows of a CSV file, and the bad rows' lines."""
...result = read_temperatures(LAB / "readings.csv")
assert isinstance(result, tuple) and len(result) == 2, "Return two lists, as a tuple."
readings, bad_lines = result
assert readings == [("Harbor", 8.5), ("Harbor", 11.0), ("Harbor", 6.5)], (
f"The good rows came back as {readings!r}."
)
assert bad_lines == [3, 5, 7], f"The bad rows' line numbers came back as {bad_lines!r}."
missing = False
try:
read_temperatures(LAB / "no-such-file.csv")
except FileNotFoundError:
missing = True
assert missing, "Let FileNotFoundError go on to the caller."
print("passed")6. Raising exceptions¶
Exercise L12.6 (LO-12.3, ★★, about 15 minutes)¶
Write
parse_reading(line), which takes a line such as"Harbor,2026-11-02,8.5"and returns the tuple("Harbor", "2026-11-02", 8.5). It raisesValueErrorwith these messages:for a line without exactly three fields:
expected 3 fields, found 2: 'Harbor,8.5', with the number found and the line’srepr;for a temperature that isn’t a number: the message
floatgives, so you don’t need to raise this one yourself;for a temperature below -90 or above 60:
temperature out of range: 85.0.
Give
d1: ifparse_readingreturnedNonefor a bad line instead of raising, which exception wouldsumraise when a caller added up the temperatures,Noneincluded?
def parse_reading(line):
"""Return the station, date, and temperature in a line of a readings file."""
...
d1 = "..."assert parse_reading("Harbor,2026-11-02,8.5") == ("Harbor", "2026-11-02", 8.5), (
"parse_reading should return the station, the date, and the temperature as a float."
)
assert parse_reading("Hilltop,2026-11-02,-90") == ("Hilltop", "2026-11-02", -90.0), (
"-90 is in the range."
)
CASES = [
("Harbor,8.5", "expected 3 fields, found 2: 'Harbor,8.5'"),
("Harbor,2026-11-02,8.5,extra", "expected 3 fields, found 4: 'Harbor,2026-11-02,8.5,extra'"),
("Harbor,2026-11-02,warm", "could not convert string to float: 'warm'"),
("Harbor,2026-11-02,85", "temperature out of range: 85.0"),
("Harbor,2026-11-02,-90.5", "temperature out of range: -90.5"),
]
for line, expected in CASES:
try:
parse_reading(line)
except ValueError as error:
assert str(error) == expected, f"For {line!r}, the message is {str(error)!r}."
else:
raise AssertionError(f"parse_reading({line!r}) should raise ValueError.")
assert d1 == "TypeError", "d1: float + None has no meaning, which is a TypeError."
print("passed")7. Finding planted bugs¶
Each of the next three exercises gives a function with a bug in it, and a report of what goes wrong. Find each bug with the method from the reading, then fix it in the answer cell:
Reproduce the bug: run the call from the report in a new cell, and compare what you get with what you expected.
Shrink the input to the smallest one that still fails.
Form a hypothesis about the cause, and test it: print values with
print(f"{name=}"), or use JupyterLab’s debugger, below.Fix the cause, rerun the answer cell, and confirm with the check.
Each exercise also asks you to choose the cause, as cause1, cause2, or cause3, before you
fix it.
To use the debugger, turn it on with the bug button at the upper right of the notebook, whose tooltip says Enable Debugger; the debugger’s sidebar opens at the right. Click just left of a line number in a cell to set a breakpoint, a red dot, then run a cell that calls the function. The code stops at that line, and the sidebar shows the Variables there. The buttons of the Callstack panel, Next, Step In, Step Out, and Continue, run the code a line at a time. Before you run the checks, click each red dot again to remove its breakpoint, or turn the debugger off with the same bug button.
Exercise L12.7 (LO-12.4, ★★, about 10 minutes)¶
moving_average(values, size) should return the mean of every run of size values in a row.
Report: moving_average([4, 8, 6, 2, 10], 2) should be [6.0, 7.0, 4.0, 6.0], but it is
[6.0, 7.0, 4.0].
Which is the cause? Set cause1 to "A", "B", or "C", then fix the function.
A: Each run takes one value too few.
B: The loop stops one starting position too early.
C: The mean divides by the wrong number.
def moving_average(values, size):
"""Return the mean of each run of size values in a row."""
means = []
for start in range(len(values) - size):
window = values[start:start + size]
means.append(sum(window) / size)
return means
cause1 = "..."assert cause1 == "B", "cause1: print start for each pass; which starting position is missing?"
assert moving_average([4, 8, 6, 2, 10], 2) == [6.0, 7.0, 4.0, 6.0], (
f"moving_average([4, 8, 6, 2, 10], 2) is {moving_average([4, 8, 6, 2, 10], 2)}."
)
assert moving_average([1, 2, 3], 3) == [2.0], "A run as long as the list gives one mean."
assert moving_average([1, 2], 3) == [], "A run longer than the list gives no means."
print("passed")Exercise L12.8 (LO-12.4, ★★, about 10 minutes)¶
median(values) should return the middle value of a list, or the mean of the two middle ones.
Report: after the next lines, the readings print in a different order from the one they
were measured in:
readings = [8.5, 11.0, 6.5]
print(median(readings))
print(readings)Which is the cause? Set cause2 to "A", "B", or "C", then fix the function so that it
leaves its argument unchanged.
A:
medianreturns the wrong value.B:
medianchanges the list that the caller passed.C:
printsorts a list before it prints it.
def median(values):
"""Return the middle value of values, or the mean of the two middle ones."""
values.sort()
middle = len(values) // 2
if len(values) % 2 == 0:
return (values[middle - 1] + values[middle]) / 2
return values[middle]
cause2 = "..."assert cause2 == "B", "cause2: print readings before and after the call to median."
readings = [8.5, 11.0, 6.5]
assert median(readings) == 8.5, f"median([8.5, 11.0, 6.5]) is {median([8.5, 11.0, 6.5])}."
assert readings == [8.5, 11.0, 6.5], f"After median(readings), readings is {readings}."
assert median([4, 1, 3, 2]) == 2.5, "median([4, 1, 3, 2]) should be 2.5."
print("passed")Exercise L12.9 (LO-12.4, ★★★, about 15 minutes)¶
total_rain(path) should add up the rain_mm column of a CSV file, skipping rows whose value
isn’t a number. Report: for the file the next cell writes, it returns 0, but the total is
14.4.
Which is the cause? Set cause3 to "A", "B", or "C", then fix the function. Fix it so
that a mistake of the same kind can’t hide again.
A:
floatcan’t convert text with a decimal point.B: The
exceptclause hides an error that isn’t about the values.C:
csv.DictReaderskips every row of a file that has an empty field.
(LAB / "rain.csv").write_text(
"date,rain_mm\n2026-11-02,0.0\n2026-11-03,2.4\n2026-11-04,\n2026-11-05,12.0\n",
encoding="utf-8",
)def total_rain(path):
"""Return the total of the rain_mm column, skipping values that aren't numbers."""
total = 0
with open(path, newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
try:
total = total + float(row["rain_m"])
except Exception:
pass
return total
cause3 = "..."assert cause3 == "B", "cause3: print the exception the except clause catches, with as error."
assert abs(total_rain(LAB / "rain.csv") - 14.4) < 1e-9, (
f"total_rain gives {total_rain(LAB / 'rain.csv')}, not 14.4."
)
(LAB / "renamed.csv").write_text("date,rain\n2026-11-02,3.0\n", encoding="utf-8")
hidden = True
try:
total_rain(LAB / "renamed.csv")
except KeyError:
hidden = False
assert not hidden, (
"A file without a rain_mm column should raise KeyError: catch only ValueError, "
"so the next misspelled name can't hide either."
)
print("passed")Summary¶
In this lab you:
read a traceback from the bottom up: the exception, the line that raised it, and the chain of calls;
predicted the exceptions that common mistakes raise;
wrote an input loop and a file reader that recover from the errors they expect, and let the others through;
raised
ValueErrorwith messages that say what was wrong; andfound three bugs by reproducing them, shrinking the input, and testing a hypothesis, one of them hidden by an
exceptclause that caught too much.
Next, the Module 12 practice has more exercises of each kind, in the terminal and in VS Code.