These exercises practice what the Module 11 reading explained. They aren’t graded.
The exercises write files, so work in a folder of your own, such as py101/m11, in a Python file
or a notebook: every relative path below is relative to the folder you run the code from. 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 log with numbered lines¶
This example writes a short log, adds a line to it, and prints it with line numbers:
from pathlib import Path
log = Path("station-log.txt")
with open(log, "w", encoding="utf-8") as file:
file.write("Gauge cleaned\n")
file.write("Battery changed\n")
with open(log, "a", encoding="utf-8") as file:
file.write("Storm: 12 mm\n")
with open(log, encoding="utf-8") as file:
for number, line in enumerate(file, start=1):
text = line.rstrip("\n")
print(f"{number}: {text}")1: Gauge cleaned
2: Battery changed
3: Storm: 12 mmMode "w" creates the file, or empties it if it exists, and mode "a" adds the third line
after the first two. The loop gives each line with its \n, which rstrip("\n") removes.
Without it, every line would be followed by a blank one: print adds a newline of its own.
Exercise 11.1 (LO-11.1, ★, about 10 minutes)¶
What does this print?
days = Path("days.txt")
with open(days, "w", encoding="utf-8") as file:
file.write("Mon\nTue\n")
with open(days, "a", encoding="utf-8") as file:
file.write("Wed")
print(days.read_text(encoding="utf-8").splitlines())
print(len(days.read_text(encoding="utf-8")))
with open(days, "w", encoding="utf-8") as file:
print(repr(days.read_text(encoding="utf-8")))
report = Path("reports") / "2026" / "nov.final.csv"
print(report.name, report.stem, report.suffix, report.parent.name)Answer
['Mon', 'Tue', 'Wed']
11
''
nov.final.csv nov.final .csv 2026The file holds Mon\nTue\nWed: three lines, the last without a newline, and 11 characters, because each \n is one character. splitlines finds the last line whether or not it ends with a newline. Mode "w" empties the file as soon as it opens, before anything is written, so the read inside the third with block finds nothing. A name’s suffix is only its last dot and what follows, so .stem keeps the first dot.
Exercise 11.2 (LO-11.1, ★★, about 15 minutes)¶
Write tail(path, count), which returns the last count lines of a text file as a list of
strings without their newlines: all of them if the file has fewer than count, and [] when
count is 0. Then check it on the worked example’s log: tail(log, 2) is
['Battery changed', 'Storm: 12 mm'], tail(log, 5) has all three lines, and tail(log, 0) is
[].
Hint
Read the lines into a list, then slice it. Work out where the slice starts for each of the three calls, and check what lines[-0:] gives.
Answer
def tail(path, count):
"""Return the last count lines of the file at path, without their newlines."""
lines = Path(path).read_text(encoding="utf-8").splitlines()
start = max(len(lines) - count, 0)
return lines[start:]
print(tail(log, 2))
print(tail(log, 5))
print(tail(log, 0))['Battery changed', 'Storm: 12 mm']
['Gauge cleaned', 'Battery changed', 'Storm: 12 mm']
[]The tempting answer, lines[-count:], works for 2 and 5 but not for 0: -0 is 0, so lines[-0:] is the whole list. Counting the start from the front, as len(lines) - count, avoids that, and max(..., 0) keeps it from going negative when count is larger than the number of lines, which would count from the end again. Path(path) lets the function take a path as a string or as a Path.
Exercise 11.3 (LO-11.1, ★★, about 10 minutes)¶
path.read_bytes() returns a file’s bytes, without decoding them, so its len is the file’s
size. In UTF-8, ï is two bytes, 0xC3 and 0xAF; in cp1252, it is one byte, 0xEF, and the
byte 0xAF is the character ¯. What does this print, and which line stops with an error?
word = Path("word.txt")
word.write_text("naïve", encoding="utf-8")
print(len("naïve"), len(word.read_bytes()))
print(word.read_text(encoding="cp1252"))
word.write_text("naïve", encoding="cp1252")
print(len(word.read_bytes()))
print(word.read_text(encoding="utf-8"))Answer
5 6
naïve
5
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xef in position 2: invalid continuation byteThe word has five characters, and its UTF-8 file has six bytes, because ï takes two. Read as cp1252, each of those two bytes is a character of its own, Ã and ¯. In cp1252, ï is one byte, 0xEF. In UTF-8, that byte starts a character three bytes long, and the next byte, the v, can’t continue one, so the last line raises UnicodeDecodeError: Python’s full error message starts with a traceback. A wrong encoding gives wrong characters without a word of warning, or it gives an error, depending on the bytes. The fix is the same either way: read a file with the encoding it was written in.
Worked example: the wettest day in a CSV file¶
This file holds a day’s rain at two stations on each line:
import csv
Path("rain.csv").write_text(
"date,station,rain_mm\n"
"2026-11-01,Harbor,3.5\n"
"2026-11-01,Hilltop,4.0\n"
"2026-11-02,Harbor,12.5\n"
"2026-11-02,Hilltop,9.0\n",
encoding="utf-8",
)To find the wettest day, add up each date’s rain in a dictionary, as Module 8 counted and grouped, then pick the date with the largest total:
totals = {}
with open("rain.csv", newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
date = row["date"]
totals[date] = totals.get(date, 0) + float(row["rain_mm"])
print(totals)
wettest = max(totals, key=lambda date: totals[date])
print("Wettest:", wettest, totals[wettest], "mm"){'2026-11-01': 7.5, '2026-11-02': 21.5}
Wettest: 2026-11-02 21.5 mmDictReader uses the header row for the keys, so row["rain_mm"] names its column, and
float converts it: added as strings, "3.5" and "4.0" would give "3.54.0".
max(totals, key=...) compares the dates by their totals, and returns the date.
Exercise 11.4 (LO-11.2, ★★, about 15 minutes)¶
Finish coldest(path), which returns the row of a CSV file with the lowest temp_c, as a
dictionary with the temperature as a float, or the first such row if two tie. With the file
below, coldest("temps.csv") is {'station': 'Hilltop', 'date': '2026-11-02', 'temp_c': -1.5}.
Then explain what it would return if you left out the conversion to float, and why.
Path("temps.csv").write_text(
"station,date,temp_c\n"
"Harbor,2026-11-02,4.5\n"
"Hilltop,2026-11-02,-1.5\n"
"Harbor,2026-11-03,-0.5\n"
"Hilltop,2026-11-03,-1.5\n",
encoding="utf-8",
)
def coldest(path):
"""Return the row with the lowest temperature, the first one if two tie."""
best = None
with open(path, newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
row["temp_c"] = ...
if ...:
best = row
return bestHint
The first row is always the best so far, because there is nothing to compare it with: test best is None first. To keep the first of two rows that tie, replace best only when the new row is strictly colder.
Answer
def coldest(path):
"""Return the row with the lowest temperature, the first one if two tie."""
best = None
with open(path, newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
row["temp_c"] = float(row["temp_c"])
if best is None or row["temp_c"] < best["temp_c"]:
best = row
return best
print(coldest("temps.csv")){'station': 'Hilltop', 'date': '2026-11-02', 'temp_c': -1.5}< keeps the first of the two rows at -1.5; <= would return the last. Without float, the temperatures stay strings, and strings compare character by character: "-0.5" comes before "-1.5" because "0" comes before "1", and both come before "4.5" because "-" comes before every digit. The function would return Harbor’s row for November 3, with '-0.5', which is the warmest of the three below zero.
Exercise 11.5 (LO-11.2, ★★★, about 20 minutes)¶
A rain gauge failed on some days, and its CSV file has an empty field for each of them:
Path("gauge.csv").write_text(
"date,rain_mm\n"
"2026-10-30,1.5\n"
"2026-10-31,\n"
"2026-11-01,0.1\n"
"2026-11-02,\n"
"2026-11-03,\n"
"2026-11-04,0.2\n",
encoding="utf-8",
)Write rain_report(source, target), which reads a file like this one and writes a CSV file with
the columns month, total_rain_mm, and days_missing: one row for each month, in order, with
the total of the days that have a value, rounded to 1 decimal place, and the number of days
whose value is missing. A missing day doesn’t count as 0 mm. For gauge.csv, the report is:
month,total_rain_mm,days_missing
2026-10,1.5,1
2026-11,0.3,2Hint
A date’s first seven characters are its month. Keep two dictionaries keyed by the month, one for the totals and one for the missing days, and set both for every month you see, even one whose days are all missing. An empty field is the string "".
Answer
def rain_report(source, target):
"""Write each month's total rain and number of missing days, from source, to target."""
totals = {}
missing = {}
with open(source, newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
month = row["date"][:7]
totals[month] = totals.get(month, 0)
missing[month] = missing.get(month, 0)
if row["rain_mm"] == "":
missing[month] = missing[month] + 1
else:
totals[month] = totals[month] + float(row["rain_mm"])
with open(target, "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["month", "total_rain_mm", "days_missing"])
for month in sorted(totals):
writer.writerow([month, round(totals[month], 1), missing[month]])
rain_report("gauge.csv", "report.csv")
for line in Path("report.csv").read_text(encoding="utf-8").splitlines():
print(line)month,total_rain_mm,days_missing
2026-10,1.5,1
2026-11,0.3,2Months written as 2026-10, with the year first and two digits for the month, sort correctly as strings, so sorted(totals) puts them in order. Three mistakes are common:
Calling
floaton every field stops at the first empty one withValueError: could not convert string to float: ''.Treating an empty field as 0 gives the right totals here, but hides the failed days: a month of broken gauge would look like a dry month.
Leaving out
roundwrites0.30000000000000004for November, because0.1 + 0.2can’t be stored exactly in a float.
A month whose days are all missing gets a total of 0, which a reader could also take for a dry month. Writing an empty field for its total would be more honest; that is a choice to make, and to explain in the program’s documentation.
Worked example: settings with defaults¶
A program that saves its settings as JSON must still work the first time it runs, before the file exists, and after an update adds a setting the old file doesn’t have. This function starts from the defaults and replaces each one the file gives:
import json
DEFAULTS = {"units": "metric", "station": "Harbor", "alerts": True}
def load_settings(path):
"""Return the settings saved at path, with the default for each one it doesn't give."""
settings = DEFAULTS.copy()
if Path(path).exists():
with open(path, encoding="utf-8") as file:
saved = json.load(file)
for name, value in saved.items():
settings[name] = value
return settings
print(load_settings("settings.json"))
Path("settings.json").write_text('{"units": "imperial"}', encoding="utf-8")
print(load_settings("settings.json")){'units': 'metric', 'station': 'Harbor', 'alerts': True}
{'units': 'imperial', 'station': 'Harbor', 'alerts': True}DEFAULTS.copy() makes a new dictionary, so changing settings never changes the defaults.
The file is JSON, so it says true where Python says True, and its strings are in double
quotes.
Exercise 11.6 (LO-11.3, ★, about 10 minutes)¶
What does this print?
print(json.dumps({"ok": True, "gap": None, "pair": (3, 4)})) print(json.dumps([1.5, "two", False])) loaded = json.loads(json.dumps({2026: ["Nov"], "count": 2})) print(loaded) print(loaded["2026"], loaded["count"] + 1) print(json.loads('["a", 1, true, null]'))Each of these lines raises an error. Which error, and why?
json.loads("{'units': 'metric'}") json.dumps({"tags": {"rain", "wind"}})
Answer
The output:
{"ok": true, "gap": null, "pair": [3, 4]} [1.5, "two", false] {'2026': ['Nov'], 'count': 2} ['Nov'] 3 ['a', 1, True, None]dumpswrites JSON, soTruebecomestrue,Nonebecomesnull, and the tuple becomes an array. On the way back, the key2026is the string'2026', and numbers stay numbers.loadsturns JSON’strueandnullinto Python’sTrueandNone.The first raises
json.JSONDecodeError, because JSON’s strings, keys included, must be in double quotes: the message isExpecting property name enclosed in double quotes: line 1 column 2 (char 1). The second raisesTypeError: Object of type set is not JSON serializable, because JSON has no sets; savesorted(tags)instead.
Exercise 11.7 (LO-11.3, ★★, about 15 minutes)¶
A game keeps its high scores in a dictionary from each level’s number to a list of scores, such
as {1: [120, 95], 2: [80]}. Write save_scores(path, scores), which saves such a dictionary as
JSON, and load_scores(path), which loads it back, returning {} if the file doesn’t exist.
load_scores must return the same dictionary that was saved, so that this prints True and then
{}:
scores = {1: [120, 95], 2: [80]}
save_scores("scores.json", scores)
print(load_scores("scores.json") == scores)
print(load_scores("no-such-file.json"))Hint
Save it, load it, and print what comes back before you write anything else. Then build a new dictionary with int applied to each key.
Answer
def save_scores(path, scores):
"""Save a dictionary from level numbers to lists of scores as JSON."""
with open(path, "w", encoding="utf-8") as file:
json.dump(scores, file, indent=2)
def load_scores(path):
"""Return the scores saved at path, with the levels as int, or {} if there is no file."""
if not Path(path).exists():
return {}
with open(path, encoding="utf-8") as file:
saved = json.load(file)
scores = {}
for level, level_scores in saved.items():
scores[int(level)] = level_scores
return scores
scores = {1: [120, 95], 2: [80]}
save_scores("scores.json", scores)
print(load_scores("scores.json") == scores)
print(load_scores("no-such-file.json"))True
{}JSON’s keys are always strings, so the file says "1" and "2", and json.load returns {'1': [120, 95], '2': [80]}. Without the conversion, the comparison prints False, and scores[1] raises KeyError. Another design avoids the problem: save a list of records, such as [{"level": 1, "scores": [120, 95]}], whose numbers stay numbers.
Worked example: flattening nested lists¶
This function returns every value inside nested lists as one flat list, in order:
def flatten(data):
"""Return the values inside nested lists, in order, as one flat list."""
if not isinstance(data, list):
return [data]
flat = []
for item in data:
flat = flat + flatten(item)
return flat
print(flatten([1, [2, [3, 4]], [], 5]))
print(flatten(7))[1, 2, 3, 4, 5]
[7]The base case is a value that isn’t a list: its flat list holds just that value. The recursive
case joins the flat lists of a list’s items. An empty list makes no calls, because its loop runs
zero times, and returns []. This table traces flatten([1, [2]]):
| Call | Case | Returns |
|---|---|---|
flatten([1, [2]]) | List: joins flatten(1) and flatten([2]) | [1] + [2], which is [1, 2] |
flatten(1) | Base case | [1] |
flatten([2]) | List: joins flatten(2) | [2] |
flatten(2) | Base case | [2] |
Exercise 11.8 (LO-11.4, ★★, about 15 minutes)¶
Write find_values(data, key), which returns a list of every value stored under key in any
dictionary inside data, at any depth, in nested dictionaries and lists. Put a dictionary’s own
value under key before the values found inside its other values. Then name the base case.
With the data below, the three calls give ['normal', 'amber', 'yellow', 'amber'], [], and
[1, 2].
feed = {
"station": "Harbor",
"alerts": [
{"level": "amber", "text": "Gale"},
{"level": "yellow", "text": "Rain", "update": {"level": "amber"}},
],
"level": "normal",
}print(find_values(feed, "level"))
print(find_values(feed, "missing"))
print(find_values([[{"a": 1}], {"b": {"a": 2}}], "a"))Hint
Follow count_values in the reading, with a list instead of a count. A dictionary adds its own value under key, if it has one, then the values found inside each of its values. A list adds the values found inside each item.
Answer
def find_values(data, key):
"""Return every value stored under key in data, at any depth, in the order found."""
found = []
if isinstance(data, dict):
if key in data:
found.append(data[key])
for value in data.values():
found = found + find_values(value, key)
elif isinstance(data, list):
for item in data:
found = found + find_values(item, key)
return found
print(find_values(feed, "level"))
print(find_values(feed, "missing"))
print(find_values([[{"a": 1}], {"b": {"a": 2}}], "a"))['normal', 'amber', 'yellow', 'amber']
[]
[1, 2]The base case is a value that is neither a dictionary nor a list, such as "Gale": it holds no keys, so the function returns [] without calling itself. The top level’s 'normal' comes first because the function adds a dictionary’s own value before it looks inside the others. Two mistakes are common. found.append(find_values(value, key)) adds each call’s list as one item, which gives nested lists that start ['normal', [], [['amber', [], []], .... A return inside the loop stops after the first value, "Harbor", and returns only ['normal'].