These exercises practice what the Module 12 reading explained. They aren’t graded.
Some happen in a terminal and in VS Code, in a folder m12 inside py101, as in the reading;
the rest work in a Python file or a notebook. Write your answer or your prediction first, then
run the code to check it. The answers are in the collapsed blocks; open one only after you have
an answer of your own.
Worked example: a traceback through Python’s own code¶
This script, list_stations.py, prints the stations listed in a JSON file:
"""Print the stations listed in stations.json."""
import json
def load_stations(path):
with open(path, encoding="utf-8") as file:
return json.load(file)
def main():
stations = load_stations("stations.json")
for name in stations:
print(name)
main()stations.json holds ['Harbor', 'Hilltop']. Running the script stops with this traceback,
from Python 3.15, with the folders before py101 and before python3.15 left out:
Traceback (most recent call last):
File ".../py101/m12/list_stations.py", line 16, in <module>
main()
~~~~^^
File ".../py101/m12/list_stations.py", line 11, in main
stations = load_stations("stations.json")
File ".../py101/m12/list_stations.py", line 7, in load_stations
return json.load(file)
~~~~~~~~~^^^^^^
File ".../python3.15/json/__init__.py", line 306, in load
return loads(fp.read(),
cls=cls, object_hook=object_hook,
parse_float=parse_float, parse_int=parse_int,
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook,
array_hook=array_hook, **kw)
File ".../python3.15/json/__init__.py", line 371, in loads
return _default_decoder.decode(s)
~~~~~~~~~~~~~~~~~~~~~~~^^^
File ".../python3.15/json/decoder.py", line 358, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
File ".../python3.15/json/decoder.py", line 376, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)Read it from the bottom up. The last line is a JSONDecodeError (its full name,
json.decoder.JSONDecodeError, says which module defines it): the text in the file isn’t valid
JSON at line 1, column 2, which is the first '. The last four frames are in Python’s own
json module, which is almost certainly working as it should, and their line numbers differ
between Python versions. Look for the last frame in your own file: line 7 of
list_stations.py, in load_stations, which called json.load. The cause isn’t in either
place, though, but in the data: JSON’s strings need double quotes, so the file should hold
["Harbor", "Hilltop"].
Exercise 12.1 (LO-12.1, ★, about 10 minutes)¶
A script, last.py, should print each station’s last reading, and stops with this traceback:
Traceback (most recent call last):
File ".../py101/m12/last.py", line 17, in <module>
main()
~~~~^^
File ".../py101/m12/last.py", line 14, in main
report({"Harbor": [8.5, 11.0, 6.5], "Hilltop": [4.0, 7.5]})
~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File ".../py101/m12/last.py", line 10, in report
print(name, last_reading(readings))
~~~~~~~~~~~~^^^^^^^^^^
File ".../py101/m12/last.py", line 5, in last_reading
return readings[len(readings)]
~~~~~~~~^^^^^^^^^^^^^^^
IndexError: list index out of rangeWhich exception was raised, in which function, and on which line?
Write the chain of calls, from the first frame to the last.
Did the script print anything before it stopped? How can you tell from the traceback alone?
What is the bug, and what is the fix?
Answer
An
IndexError, inlast_reading, on line 5.<module>(line 17) calledmain, which calledreporton line 14, which calledlast_readingon line 10.No. The exception happened inside the
printcall on line 10, for the first station, while Python was still working out what to print.printnever ran, so Harbor wasn’t printed.A list of length 3 has positions 0 to 2, so
readings[len(readings)]is one past the end. The last item isreadings[len(readings) - 1], or, more simply,readings[-1]. Here the last frame is where the mistake is.
Exercise 12.2 (LO-12.1, ★★, about 10 minutes)¶
This script, syntax.py, has a mistake:
temps = [8.5, 11.0, 6.5]
total = sum(temps
mean = total / len(temps)
print(f"Mean: {mean:.1f}")Running it prints this, and nothing else:
File ".../py101/m12/syntax.py", line 2
total = sum(temps
^
SyntaxError: '(' was never closedWhy does the message have no
Traceback (most recent call last):heading and no chain of calls?Why didn’t the script print anything, not even from the lines that come before the mistake?
Where does the
^point, and where does the fix go?
Answer
A
SyntaxErrorhappens while Python reads the file, before any of it runs, so no function has been called: there is no chain of calls to show.For the same reason. Python reads the whole file before it runs the first line, and a file with a syntax error never runs at all.
The
^points at the(that was opened and never closed, on line 2. The fix is a)at the end of that line:total = sum(temps). With other mistakes, the^can point after the real mistake, at the place Python stopped making sense of the code; then look at the line before it.
Worked example: skipping the lines that aren’t numbers¶
A file of prices has a few lines that aren’t numbers. This code adds up the rest, and records the line numbers it skipped:
from pathlib import Path
Path("prices.txt").write_text("2.50\n1.25\nfree\n\n3.00\n", encoding="utf-8")
total = 0
skipped = []
with open("prices.txt", encoding="utf-8") as file:
for number, line in enumerate(file, start=1):
try:
price = float(line)
except ValueError:
skipped.append(number)
else:
total = total + price
print(f"Total: {total:.2f}")
print("Skipped lines:", skipped)Total: 6.75
Skipped lines: [3, 4]float ignores spaces and newlines around a number, so float("2.50\n") is 2.5, but free and
the empty line raise ValueError. The try block holds only the conversion; adding to the total
happens in else, only when the conversion worked. The open is outside the try statement, so
a missing file still stops the program with FileNotFoundError: that isn’t a bad line to skip,
and hiding it would report a total of 0.00 for a file that isn’t there.
Exercise 12.3 (LO-12.2, ★★, about 15 minutes)¶
What is wrong with this function? Rewrite it so that it skips lines that aren’t numbers, lets a
missing file raise FileNotFoundError, and raises ValueError with a clear message for a file
with no numbers in it.
def average_from_file(path):
"""Return the average of the numbers in a file, one on each line."""
try:
values = []
with open(path, encoding="utf-8") as file:
for line in file:
values.append(float(line))
return sum(values) / len(values)
except Exception:
return 0Hint
List the different things that make this function return 0, and ask, for each one, whether 0 is a truthful answer.
Answer
Four different problems all return 0: a missing file, an empty file (ZeroDivisionError), a single bad line (ValueError, which also throws away every good line), and any bug inside the try block. A caller can’t tell any of them from a file whose numbers really average 0.
def average_from_file(path):
"""Return the average of the numbers in a file, one on each line, skipping other lines."""
values = []
with open(path, encoding="utf-8") as file:
for line in file:
try:
values.append(float(line))
except ValueError:
pass
if not values:
raise ValueError(f"no numbers in {path}")
return sum(values) / len(values)
print(average_from_file("prices.txt"))
Path("words.txt").write_text("none\nhere\n", encoding="utf-8")
try:
average_from_file("words.txt")
except ValueError as error:
print("ValueError:", error)2.25
ValueError: no numbers in words.txtThe try statement now holds only the conversion, and catches only ValueError. A missing file raises FileNotFoundError on its own, because nothing catches it. An empty result raises a ValueError whose message says what was wrong and in which file, instead of dividing by zero. pass is the statement that does nothing, which is all a skipped line needs.
Exercise 12.4 (LO-12.2, ★★, about 15 minutes)¶
Write a script, adder.py, that asks for numbers, one at a time, and adds them up. It skips text
that isn’t a number, with a message. When the user presses Ctrl+C, or ends the input with Ctrl+D
(Ctrl+Z then Enter on Windows), it prints the total and stops, without a traceback. Run it in a
terminal, and check that a session looks like this one, which ends with Ctrl+D:
Number: 2.5
Number: ten
'ten' isn't a number; skipped.
Number: 4
Number:
Total: 6.5Hint
You need two try statements: one inside the loop, around the conversion, and one around the whole loop, for KeyboardInterrupt and EOFError. Print the total after the outer one.
Answer
"""Add up the numbers the user types, until the input ends."""
def main():
total = 0
try:
while True:
text = input("Number: ")
try:
total = total + float(text)
except ValueError:
print(f"{text!r} isn't a number; skipped.")
except (KeyboardInterrupt, EOFError):
print()
print(f"Total: {total}")
if __name__ == "__main__":
main()The inner try handles one bad line and lets the loop go on; the outer one ends the loop. Each handles the exceptions it can do something about, at the level where it can do it. Ending the input is the normal way to finish here, so the total is printed after the outer statement, whichever way the loop ended. print() ends the line the last prompt was on.
Exercise 12.5 (LO-12.2, ★, about 10 minutes)¶
What does this print?
def inner(text):
try:
return int(text)
finally:
print("inner done")
def outer(text):
try:
value = inner(text)
except ValueError:
print("outer caught it")
return 0
return value * 10
print(outer("3"))
print(outer("three"))Answer
inner done
30
inner done
outer caught it
0inner has no except clause, so the ValueError from int("three") goes on to its caller, outer, which handles it. finally runs on the way out of inner either way: before the return value reaches outer, and before the exception does. An exception travels up the chain of calls, the same chain a traceback shows, until an except clause names it.
Exercise 12.6 (LO-12.3, ★★, about 10 minutes)¶
For each function, should it raise an exception or return a special value when it can’t give the usual answer? Say why.
average(values), given an empty list.find_word(words, target), which a search box uses to find the position of a word that the user typed, given a word that isn’t in the list.load_config(path), which reads the settings a program can’t start without, given a path with no file.get_setting(settings, name, default), given a name that isn’t insettings.
Answer
Raise
ValueError. Any number returned, such as 0, would look like a real average. The standard library’sstatistics.mean([])raisesStatisticsError, which is a kind ofValueError, with the messagemean requires at least one data point.Return a special value, such as
None. A word that isn’t there is a normal result of a search, and the search box will check for it to say “not found”. Python’s ownlist.indexraisesValueErrorinstead, which works too, if the caller catches it.Raise. The program can’t run without its settings, so
FileNotFoundError, or aValueErrorthat names the path, should reachmain, which can report it and stop.Return the default. The caller passed one, so a missing name is expected and already handled, as with a dictionary’s
get.
Exercise 12.7 (LO-12.3, ★★, about 15 minutes)¶
Write parse_time(text), which turns a time such as "09:30" into the number of minutes since
midnight, 570. It raises ValueError:
with the message
expected HH:MM, got '930'for text without exactly one:, showing the text’srepr;with the message
intgives for an hour or a minute that isn’t a whole number;with the message
hour out of range: 24for an hour outside 0–23, andminute out of range: 60for a minute outside 0–59.
Then check it on "09:30", "23:59", "930", "9:3o", "24:00", and "12:60".
Answer
def parse_time(text):
"""Return the minutes since midnight of a time written as HH:MM."""
parts = text.split(":")
if len(parts) != 2:
raise ValueError(f"expected HH:MM, got {text!r}")
hour = int(parts[0])
minute = int(parts[1])
if not 0 <= hour <= 23:
raise ValueError(f"hour out of range: {hour}")
if not 0 <= minute <= 59:
raise ValueError(f"minute out of range: {minute}")
return hour * 60 + minute
for text in ["09:30", "23:59", "930", "9:3o", "24:00", "12:60"]:
try:
print(text, parse_time(text))
except ValueError as error:
print(text, "ValueError:", error)09:30 570
23:59 1439
930 ValueError: expected HH:MM, got '930'
9:3o ValueError: invalid literal for int() with base 10: '3o'
24:00 ValueError: hour out of range: 24
12:60 ValueError: minute out of range: 60int raises its own ValueError for 3o, with the text in its message, so the function doesn’t need to catch and raise it again. Every problem reaches the caller as ValueError, which one except clause handles. int also accepts spaces and a sign, so parse_time("-1:00") raises hour out of range: -1, and parse_time(" 9:30") is 570: decide whether that is what you want, and say so in the docstring.
Worked example: a bug found by shrinking¶
count_long_words(text, length) should count the words with at least length letters:
def count_long_words(text, length):
"""Return how many words in text have at least length letters."""
count = 0
for word in text.split():
if len(word) > length:
count = count + 1
return count
print(count_long_words("Rain is due at noon", 4))0Reproduce. “Rain” and “noon” have four letters each, so the answer should be 2, not 0.
Shrink.
count_long_words("Rain", 4)is 0, butcount_long_words("Rains", 4)is 1.Hypothesize. A word of exactly
lengthletters isn’t counted, so the comparison is wrong at the boundary.Test. Printing
f"{word=} {len(word)=} {len(word) > length=}"inside the loop showsword='Rain' len(word)=4 len(word) > length=False, which confirms it.Fix and confirm. “At least” means
>=. Withlen(word) >= length, the call gives 2,"Rain"alone gives 1, and"Rains"still gives 1.
Shrinking turned a sentence into one word and two lengths, the boundary and one past it. Bugs cluster at boundaries such as these: an empty input, the first or last item, and a value equal to a limit.
Exercise 12.8 (LO-12.4, ★★, about 10 minutes)¶
This function should put each word’s first letter in capitals:
def capitalize_words(text):
"""Return text with the first letter of each word in capitals."""
words = text.split(" ")
result = []
for word in words:
result.append(word[0].upper() + word[1:])
return " ".join(result)It works on most sentences, but stops with IndexError: string index out of range on this one:
capitalize_words("rain later today, clearing from the west by evening")Shrink the input to the smallest one that fails, form a hypothesis, and fix the function so that it keeps the text’s spacing as it is.
Hint
Remove words from either end of the sentence as long as it still fails. Then print words for what is left.
Answer
The smallest failing inputs are "a b", two spaces in a row, and "", the empty string. text.split(" ") splits at every single space, so two spaces in a row give an empty word: "a b".split(" ") is ['a', '', 'b'], and "".split(" ") is ['']. An empty word has no word[0]. A slice past the end of a string is empty instead of an error, so word[:1] works for every word:
def capitalize_words(text):
"""Return text with the first letter of each word in capitals."""
words = text.split(" ")
result = []
for word in words:
result.append(word[:1].upper() + word[1:])
return " ".join(result)
print(repr(capitalize_words("rain later today, clearing from the west by evening")))
print(repr(capitalize_words("")))'Rain Later Today, Clearing From The West By Evening'
''text.split() without an argument would skip the empty words too, but joining the result with " " would turn the double space into a single one, which changes the text.
Exercise 12.9 (LO-12.4, ★★★, about 20 minutes)¶
Save this as means.py, and find the bug with VS Code’s debugger, following the steps in the
reading. Report: Hilltop’s mean is 18.75, but its readings are 4.0 and 7.5.
def station_means(readings):
"""Return each station's mean temperature, from a dictionary of lists."""
means = {}
total = 0
for station, temps in readings.items():
for temp in temps:
total = total + temp
means[station] = total / len(temps)
return means
print(station_means({"Harbor": [8.5, 11.0, 6.5], "Hilltop": [4.0, 7.5]}))Write down each step of the method as you go: what you reproduced, the smallest input that fails, your hypothesis, what you looked at to test it, and the fix.
Hint
Set a breakpoint on the line for temp in temps:, and watch total in VARIABLES each time the program stops there. What should total be when a new station starts?
Answer
Reproduce. The script prints
{'Harbor': 8.666666666666666, 'Hilltop': 18.75}. Hilltop should be (4.0 + 7.5) / 2, which is 5.75.Shrink.
station_means({"A": [1.0], "B": [1.0]})gives{'A': 1.0, 'B': 2.0}. The first station is right and the second is wrong, with one reading each.Hypothesize. The second station’s total still holds the first station’s readings.
Test. With a breakpoint on
for temp in temps:, the program stops twice. The first time, VARIABLES showsstationas'Harbor'andtotalas0. After Continue, it showsstationas'Hilltop'andtotalas26.0, Harbor’s sum. The hypothesis is right.Fix and confirm. Start each station’s total at 0, by moving
total = 0inside the outer loop, beforefor temp in temps:. The script then prints{'Harbor': 8.666666666666666, 'Hilltop': 5.75}, and the small case gives{'A': 1.0, 'B': 1.0}.
def station_means(readings):
"""Return each station's mean temperature, from a dictionary of lists."""
means = {}
for station, temps in readings.items():
total = 0
for temp in temps:
total = total + temp
means[station] = total / len(temps)
return means
print(station_means({"Harbor": [8.5, 11.0, 6.5], "Hilltop": [4.0, 7.5]}))
print(station_means({"A": [1.0], "B": [1.0]})){'Harbor': 8.666666666666666, 'Hilltop': 5.75}
{'A': 1.0, 'B': 1.0}A variable that should start fresh for each item of an outer loop must be set inside that loop. The first station was right, which is why testing a single station would never have found this bug.