Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Objectives: LO-14.1–14.4, LO-15.1–15.3, LO-16.1–16.4, LO-17.1–17.3, and LO-18.1–18.3, and, revisited, LO-7.2, LO-8.4, LO-11.4, LO-12.2, and LO-12.3
Prerequisites: Modules 1–18
Time: 2 hours for the 20 questions, worth 100 points, and about 30 minutes more to check your answers and review what you missed

This self-test mixes questions from the whole course, most of them on Modules 14–18: classes, inheritance and special methods, generators and decorators, databases and web APIs, and packaging. It isn’t graded. Take it after Module 18 and before you release your capstone project, in one sitting. The answers are in the collapsed blocks after each question; open them only once you have written all of yours.

How to take it

  1. Set aside 2 hours without interruptions. Use paper and a pen, with no computer, phone, or notes: the effort of recalling without help is what makes this practice work.

  2. Write an answer to every question before you open any answer. Each question’s heading gives its objectives and its points.

  3. Open the answers and score yourself. Each answer says how its points are given. The points are only for scoring yourself: the course has no grades.

  4. For each question you missed, its objective IDs name the modules to review: for example, LO-16.2 belongs to Module 16. Run the question’s code to see the answer for yourself.

Rules for your answers

Questions

Question 1 (LO-14.1, LO-14.2, 6 points)

class Thermostat:
    """A thermostat whose target is always from 5 to 30 °C."""

    def __init__(self, target):
        self.set(target)

    def set(self, target):
        if not 5 <= target <= 30:
            raise ValueError(f"target must be from 5 to 30, not {target}")
        self.target = target

    def nudge(self, degrees):
        self.set(self.target + degrees)


hall = Thermostat(18)
hall.nudge(4)
print(hall.target)
try:
    hall.nudge(10)
except ValueError as error:
    print(error)
print(hall.target)
try:
    Thermostat(40)
except ValueError as error:
    print(error)

(a) (3 points) What does it print?

(b) (1 point) State the class’s invariant.

(c) (2 points) A colleague adds the line hall.target = 99 at the end. Python runs it without complaint. What does it do to the invariant, and which two conventions from Module 14 should have stopped your colleague?

Answer

(a)

22
target must be from 5 to 30, not 32
22
target must be from 5 to 30, not 40

nudge(10) calls set(32), which raises before it changes anything, so the target stays 22. Thermostat(40) raises in __init__, so no thermostat with a target of 40 ever exists. One point for the first 22, one for the message with 32 and the 22 after it, and one for the last line.

(b) The target is always from 5 to 30 °C, inclusive. (The docstring states it.)

(c) It breaks the invariant: the object now holds a target of 99, and no check ran. The conventions: code outside a class changes an object only through its methods, such as set; and a name that starts with one underscore, such as self._target, marks an attribute as internal to the class. Python enforces neither. One point for each convention.

Question 2 (LO-14.3, 5 points)

from dataclasses import dataclass


@dataclass(frozen=True)
class Reading:
    station: str
    temp_c: float


class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y


a = Reading("Harbor", 8.5)
b = Reading("Harbor", 8.5)
print(a == b, a is b)
print(a)
print(Point(1, 2) == Point(1, 2))
a.temp_c = 9.0

(a) (3 points) What do the three print calls print?

(b) (1 point) What happens at the last line?

(c) (1 point) Why does Point(1, 2) == Point(1, 2) give the answer it does, and what would change it?

Answer

(a)

True False
Reading(station='Harbor', temp_c=8.5)
False

The dataclass generates __eq__, which compares the fields, and __repr__, which shows them; is still asks whether two names refer to one object, and these are two. One point for each line.

(b) dataclasses.FrozenInstanceError: cannot assign to field 'temp_c'. frozen=True refuses every assignment after __init__.

(c) Without an __eq__ of its own, == on objects compares identity, as is does, and these are two objects. Defining __eq__, or making Point a dataclass, makes it True.

Question 3 (LO-14.4, 4 points)

def average(values: list[float]) -> float:
    return sum(values) / len(values)


print(average([1, 2]))
print(average((3, 4)))
print(average("ab"))

(a) (2 points) What happens when you run it?

(b) (2 points) mypy reports two of the three calls. Which two, and why does it report one that worked when the program ran?

Answer

(a) It prints 1.5 and 3.5, then stops with TypeError: unsupported operand type(s) for +: 'int' and 'str', raised inside sum. Python doesn’t check hints while the program runs, so the tuple and the string get into average, and only the string reaches an operation it doesn’t support. One point for the two numbers, and one for the error.

(b) The tuple and the string: Argument 1 to "average" has incompatible type "tuple[int, int]"; expected "list[float]", and the same with "str". mypy checks each call against the hint without running anything. The hint promises a list, and a tuple isn’t one, even though this function happens to work with it; if tuples should be allowed, the hint should say so. The list [1, 2] is fine, because a type checker lets an int stand where a float is expected. One point for naming both calls, and one for the reason.

Question 4 (LO-15.1, 5 points)

class Gauge:
    def __init__(self, name):
        self.name = name
        self.readings = []

    def add(self, value):
        self.readings.append(value)

    def describe(self):
        return f"{self.name}: {len(self.readings)} readings"


class CheckedGauge(Gauge):
    def __init__(self, name, limit):
        super().__init__(name)
        self.limit = limit

    def add(self, value):
        if value > self.limit:
            raise ValueError(f"{value} is above the limit, {self.limit}")
        super().add(value)

    def describe(self):
        return super().describe() + f", limit {self.limit}"


gauge = CheckedGauge("Hilltop", 50)
gauge.add(12)
try:
    gauge.add(80)
except ValueError as error:
    print(error)
print(gauge.describe())
print(isinstance(gauge, Gauge), isinstance(Gauge("Harbor"), CheckedGauge))

(a) (3 points) What does it print?

(b) (2 points) Suppose CheckedGauge.__init__ left out the line super().__init__(name). What would happen at gauge.add(12), and why?

Answer

(a)

80 is above the limit, 50
Hilltop: 1 readings, limit 50
True False

add(80) raises before it calls super().add, so only 12 is stored. A CheckedGauge is a Gauge, but a Gauge isn’t a CheckedGauge. One point for each line.

(b) AttributeError: 'CheckedGauge' object has no attribute 'readings'. Gauge.__init__ never runs, so neither name nor readings is set, and super().add appends to self.readings, which doesn’t exist. One point for the error, and one for the reason.

Question 5 (LO-15.2, 5 points)

You are writing a class Station, which has a name, a Thermometer, and a RainGauge (classes that already exist), and a method report() that uses both. A teammate suggests class Station(RainGauge):, so that station.add(4.2) records rain without any new code.

In three or four sentences, say whether you would use inheritance or composition for Station, and why. Then write the start of the class: its class line and its __init__.

Answer

Composition. A station isn’t a kind of rain gauge; it has a rain gauge, and a thermometer too, so it fails Module 15’s test for inheritance. Inheriting would make every method of RainGauge part of Station, including ones that make no sense for a station, and every user of Station would depend on RainGauge never changing. With composition, Station offers only the methods it chooses, such as add_rain, which passes the work to its gauge, and a station with two gauges later needs no new design.

class Station:
    def __init__(self, name, thermometer, gauge):
        self.name = name
        self.thermometer = thermometer
        self.gauge = gauge

Two points for choosing composition with the “is a” or “has a” reasoning, two for a concrete problem that inheritance would cause, and one for the class.

Question 6 (LO-15.3, 5 points)

class Distance:
    def __init__(self, km):
        self.km = km

    def __add__(self, other):
        return Distance(self.km + other.km)

    def __lt__(self, other):
        return self.km < other.km

    def __repr__(self):
        return f"Distance({self.km})"


legs = [Distance(5), Distance(2), Distance(8)]
print(legs[0] + legs[1])
print(sorted(legs))
print(max(legs))
print(sum(legs, Distance(0)))
print(sum(legs))

(a) (3 points) What do the first four print calls print?

(b) (1 point) What does the last one do, and why?

(c) (1 point) sorted and max were written long before Distance, yet they work with it. What is the name for this, and what do they need from Distance?

Answer

(a)

Distance(7)
[Distance(2), Distance(5), Distance(8)]
Distance(8)
Distance(15)

+ calls __add__, sorted and max compare with __lt__, and print shows each object with __repr__, in the list too. One point for the first line, one for the second, and one for the last two.

(b) It raises TypeError: unsupported operand type(s) for +: 'int' and 'Distance'. sum starts from 0 unless it is given a start, and 0 + Distance(5) asks int to add a Distance, which it can’t. With Distance(0) as the start, every addition is a Distance plus a Distance.

(c) Duck typing: they don’t check the type of what they get, only that it supports the operations they use. Here they need <, which __lt__ provides.

Question 7 (LO-15.3, LO-16.1, 5 points)

class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current == 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1


def countdown(start):
    while start > 0:
        yield start
        start -= 1


c = Countdown(3)
print(list(c), list(c))
g = countdown(3)
print(next(g), list(g), list(g))
print(list(countdown(2)), list(countdown(2)))

(a) (3 points) What does it print?

(b) (2 points) Why is the second list(c) empty, when the last line prints two full lists?

Answer

(a)

[3, 2, 1] []
3 [2, 1] []
[2, 1] [2, 1]

One point for each line.

(b) Countdown is its own iterator: __iter__ returns the object itself, and the first list(c) calls __next__ until it raises StopIteration, which leaves current at 0. Nothing resets it, so the second list gets nothing at once. A generator object works the same way, as g shows: next(g) takes 3, the first list(g) takes the rest, and the second finds it used up. The last line works because each call countdown(2) makes a new generator. One point for “the iterator is used up and doesn’t restart”, and one for “each call makes a new generator”.

Question 8 (LO-16.1, 5 points)

def numbers():
    for n in range(1, 4):
        print("making", n)
        yield n * 10


pipeline = (n + 1 for n in numbers())
print("start")
for value in pipeline:
    print("got", value)

(a) (3 points) What does it print?

(b) (2 points) In Module 16, adding up a million squares from a list held about 40 MB at its peak, and from a generator expression about 0.5 KB. Name a task where you would still choose a list, and say why a generator wouldn’t do.

Answer

(a)

start
making 1
got 11
making 2
got 21
making 3
got 31

Neither the generator nor the generator expression runs any code until the loop asks for a value, so start comes first, and then each value is made just before it is used. One point for start first, one for “making” and “got” alternating, and one for the values.

(b) Any task that needs the items more than once, or out of order: going through the readings twice (once for the mean, once for the readings above it), sorting them, taking len, or reading the item at an index. A generator gives each item once, in order, and is then used up. One point for the task, and one for the reason.

Question 9 (LO-16.2, 5 points)

from itertools import chain, groupby, islice

days = ["Mon", "Tue", "Wed"]
rain = [0.0, 2.5, 2.5, 0.0, 4.1, 0.0]
print(list(islice(rain, 2, 5)))
print(list(chain(days, ["Thu"])))
print([(key, len(list(group))) for key, group in groupby(rain)])
print(any(r > 4 for r in rain), all(r > 0 for r in rain))
print(max(zip(days, rain), key=lambda pair: pair[1]))

What does it print? (1 point for each line)

Answer
[2.5, 0.0, 4.1]
['Mon', 'Tue', 'Wed', 'Thu']
[(0.0, 1), (2.5, 2), (0.0, 1), (4.1, 1), (0.0, 1)]
True False
('Tue', 2.5)
  • islice(rain, 2, 5) takes the items at positions 2, 3, and 4, as the slice rain[2:5] would.

  • groupby groups only items that are next to each other, so 0.0 makes three separate groups. To group equal values wherever they are, sort first.

  • zip stops at the shorter input, so it makes three pairs. max with a key compares the rain, and returns the first of two equal largest values, Tuesday’s.

Question 10 (LO-16.3, 6 points)

(a) (4 points) Write a decorator counted that counts how many times the decorated function is called, in an attribute calls of the function it returns, starting at 0. The decorated function must keep its name and docstring.

(b) (2 points) With your decorator, what does this print? What would its last line print if your decorator didn’t keep the name and docstring?

@counted
def greet(name):
    """Return a greeting."""
    return f"Hello, {name}!"


print(greet("Ada"))
greet("Grace")
print(greet.calls, greet.__name__, greet.__doc__)
Answer

(a)

import functools


def counted(function):
    """Count the calls of function, in the wrapper's calls attribute."""
    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        wrapper.calls += 1
        return function(*args, **kwargs)
    wrapper.calls = 0
    return wrapper

One point for a wrapper that calls function with *args and **kwargs and returns its result, one for counting in wrapper.calls, one for starting it at 0 outside wrapper, and one for functools.wraps.

(b)

Hello, Ada!
2 greet Return a greeting.

Without functools.wraps, the last line would be 2 wrapper None: greet now names the wrapper, which has its own name and no docstring. One point for each part.

Question 11 (LO-16.3, 4 points)

from functools import cache

calls = []


@cache
def ways(n):
    """Count the ways to climb n stairs, one or two at a time."""
    calls.append(n)
    if n <= 1:
        return 1
    return ways(n - 1) + ways(n - 2)


print(ways(10), len(calls))
print(ways(12), len(calls))
print(ways(5), len(calls))

(a) (3 points) What does it print?

(b) (1 point) Putting @cache on a function that takes a list works until the function is called. What happens then, and why?

Answer

(a)

89 11
233 13
8 13

With the cache, the body runs once for each n. ways(10) runs it for 10, 9, … 0: 11 times. ways(12) needs only 12 and 11, since ways(10) is stored, and ways(5) is stored already. One point for each line; give yourself the point for a line whose second number follows from your first line’s.

(b) TypeError: unhashable type: 'list'. The cache is a dictionary whose keys are the arguments, and a list can’t be a dictionary key, because it can change (Module 8).

Question 12 (LO-16.4, LO-12.2, 5 points)

from contextlib import contextmanager


@contextmanager
def announce(label):
    print("start", label)
    try:
        yield label.upper()
    finally:
        print("stop", label)


with announce("a") as name:
    print("inside", name)
try:
    with announce("b"):
        print(1 / 0)
except ZeroDivisionError:
    print("caught")

(a) (3 points) What does it print?

(b) (2 points) Suppose announce had no try and finally: just the first print, the yield, and the second print. What would the second with statement and the except print, and why?

Answer

(a)

start a
inside A
stop a
start b
stop b
caught

The value after yield is what as receives. When the block raises, the exception comes out of the yield, the finally clause runs, and the exception carries on to the except outside. One point for the first three lines, one for stop b, and one for caught last.

(b) start b, then caught. The exception is raised at the yield, so the line after it never runs. finally is what makes clean-up run whether or not the block succeeds (Module 12).

Question 13 (LO-17.1, 6 points)

A database has this table, which holds three readings: Harbor on 2026-11-02 with 1.2 mm, Hilltop on 2026-11-02 with 3.1 mm, and Harbor on 2026-11-03 with 7.4 mm.

CREATE TABLE readings (
    station TEXT NOT NULL,
    day TEXT NOT NULL,
    rain_mm REAL NOT NULL CHECK (rain_mm >= 0)
)

(a) (2 points) Write total_between(connection, station, first, last), which returns the station’s total rain_mm from day first to day last, inclusive, with every value in a placeholder. What does it return for a station with no readings?

(b) (2 points) What does this print, and how many rows does the table hold after it?

insert = "INSERT INTO readings VALUES (?, ?, ?)"
try:
    with connection:
        connection.execute(insert, ("Harbor", "2026-11-04", 2.0))
        connection.execute(insert, ("Mill Lane", "2026-11-04", -1.0))
except sqlite3.IntegrityError as error:
    print("IntegrityError:", error)

(c) (2 points) Another function builds its query as f"SELECT day, rain_mm FROM readings WHERE station = '{name}'". Give a value of name that makes it return every row, and explain how it works.

Answer

(a)

def total_between(connection, station, first, last):
    """Return a station's total rain from day first to day last, inclusive."""
    row = connection.execute(
        "SELECT SUM(rain_mm) FROM readings WHERE station = ? AND day BETWEEN ? AND ?",
        (station, first, last),
    ).fetchone()
    return row[0]

day >= ? AND day <= ? works as well as BETWEEN, which includes both ends; dates in the form 2026-11-02 sort in the same order as text. For Harbor in November it returns 8.6. For a station with no readings, SUM gives NULL, so it returns None. One point for the query with three placeholders, and one for None.

(b) It prints IntegrityError: CHECK constraint failed: rain_mm >= 0, and the table still holds 3 rows: the with block is one transaction, so the failed insert rolls back the Harbor insert before it too. One point for each.

(c) x' OR '1'='1. The query becomes WHERE station = 'x' OR '1'='1': the value’s first quotation mark closes the string, OR '1'='1' is true for every row, and the f-string’s own closing mark completes '1'. Any value that does the same earns the points. One point for a value that works, and one for the explanation. The fix is a placeholder, which sends the name as a value that can’t become part of the SQL.

Question 14 (LO-17.2, LO-12.3, 5 points)

Module 17’s get_json(url, key, timeout=5.0) sends a Request with urlopen, and returns the JSON it reads. (1 point each)

(a) Which exception does it raise when the server answers with status 404?

(b) Which does it raise when nothing is listening at the address?

(c) Which does it raise when the server accepts the request but sends its answer too slowly?

(d) A try statement handles both HTTPError and URLError. Why must except HTTPError come first?

(e) Module 17’s station(name, key) returns None when the service answers with a 404, but lets the HTTPError for a 401, a wrong key, go on to its caller. Why return a special value in one case and raise in the other?

Answer

(a) urllib.error.HTTPError, whose code is 404.

(b) urllib.error.URLError, with a ConnectionRefusedError as its reason.

(c) TimeoutError, when reading the answer takes longer than the timeout.

(d) HTTPError is a subclass of URLError, and Python uses the first except clause that matches. With except URLError first, it would catch every HTTP error too, and the HTTPError clause would never run.

(e) “No such station” is an ordinary answer that a caller can deal with, as with a dictionary’s get. A refused key means the program is set up wrong; if station returned None for it too, a wrong key would look like a missing station, and the caller would never find out. An exception can’t be ignored by accident, and its message, HTTP Error 401: Unauthorized, says what is wrong.

Question 15 (LO-17.3, 5 points)

weather.py holds:

import json
from urllib.request import urlopen


def temperature(url):
    """Return the temp_c value of the JSON at url."""
    with urlopen(url, timeout=5) as response:
        return json.load(response)["temp_c"]

and test_weather.py holds:

from unittest.mock import patch
from urllib.error import URLError

import pytest

import weather


def test_service_down():
    with patch("urllib.request.urlopen", side_effect=URLError("down")):
        with pytest.raises(URLError):
            weather.temperature("http://127.0.0.1:9/now")

(a) (3 points) The test passes. Does it test what it seems to? Explain what really happens when it runs, and fix it.

(b) (2 points) temperature should send an API key, which the program reads from the environment variable WEATHER_KEY. Why read it from the environment rather than write it in weather.py, and what should you do if a key has already been committed to a public repository?

Answer

(a) No. weather.py imported urlopen into its own namespace, so temperature looks up weather.urlopen, which the patch didn’t replace. The test makes a real request to port 9 of this computer; it passes only because nothing is listening there, so the real urlopen raises URLError too. On another computer, or with a real address, it could fail or hang. Patch the name where the code looks it up:

    with patch("weather.urlopen", side_effect=URLError("down")):

One point for “it makes a real request”, one for why, and one for the fix.

(b) Code is copied, shared, and published with its repository, and a key in it goes wherever the code goes; the environment keeps the key on the computer that uses it. Once a key is committed, deleting the line isn’t enough, because the commit that added it stays in the history on every clone: revoke the key with the service, and make a new one. One point for each part.

Question 16 (LO-18.1, 5 points)

A project in the src layout, with its package in src/wordtally, has this in its pyproject.toml:

[project]
name = "wordtally"
version = "1.2.0"
requires-python = ">=3.12"
dependencies = []

[project.scripts]
tally = "wordtally.cli:run"

(a) (2 points) After python -m pip install -e ., a user runs tally notes.txt. What runs, and where does the command’s exit status come from?

(b) (2 points) You then change the code in src/wordtally/counting.py, and change version to "1.3.0". Without installing again, which of the two changes does tally see?

(c) (1 point) Before the install, python -m pytest in the project’s folder failed with ModuleNotFoundError: No module named 'wordtally'. Why, and why is that useful?

Answer

(a) The tally command that pip wrote into the environment imports the module wordtally.cli and calls its function run, which finds notes.txt in sys.argv (for example, through argparse). The command exits with the status run returns. One point for each part.

(b) Only the code change. An editable install points the environment at src, so new code runs at once, but the version is part of what pip recorded at install time, so tally keeps reporting 1.2.0 until you install again. One point for each change.

(c) The package is inside src, which isn’t on Python’s search path, so the tests can import it only once it is installed. That way they test the installed package, which is what users get, and not loose files in the folder.

Question 17 (LO-18.2, LO-7.2, 5 points)

Ruff reports B006 Do not use mutable data structures for argument defaults for the first line of this program:

def add_tag(tag, tags=[]):
    tags.append(tag)
    return tags


print(add_tag("rain"))
print(add_tag("wind"))
print(add_tag("fog", []))

(a) (2 points) What does it print, and why is that a bug?

(b) (1 point) Fix add_tag.

(c) (2 points) mypy, in strict mode, reports error: Item "None" of "str | None" has no attribute "upper" [union-attr] for the last line of this program. When would that line crash? Fix it without # type: ignore.

def find(names: list[str], prefix: str) -> str | None:
    """Return the first name that starts with prefix, or None if there is none."""
    for name in names:
        if name.startswith(prefix):
            return name
    return None


print(find(["Harbor", "Hilltop"], "Hi").upper())
Answer

(a)

['rain']
['rain', 'wind']
['fog']

The default list is made once, when Python defines the function, so every call that leaves out tags appends to the same list: the second call sees the first call’s tag (Module 7’s aliasing). The third call passes a new list, so it is unaffected. One point for the output, and one for the reason.

(b)

def add_tag(tag, tags=None):
    if tags is None:
        tags = []
    tags.append(tag)
    return tags

(c) When no name starts with the prefix, as with "Mi": find returns None, and None.upper() raises AttributeError: 'NoneType' object has no attribute 'upper'. With "Hi" it happens to work, which is why a test of this data alone wouldn’t find it. Check before using the value:

name = find(["Harbor", "Hilltop"], "Hi")
if name is None:
    print("no station starts with Hi")
else:
    print(name.upper())

One point for when it crashes, and one for the fix.

Question 18 (LO-18.3, 5 points)

rainkit is at version 3.2.1. (1 point each)

(a)–(c) Give the next version for a release whose only change is:

(d) Under which changelog headings, in Keep a Changelog’s format, do the three changes go?

(e) Write the two Git commands that tag release 3.3.0 and send the tag to GitHub.

Answer

(a) 3.2.2: a bug fix raises PATCH.

(b) 3.3.0: a new feature that breaks nothing raises MINOR, and resets PATCH to 0.

(c) 4.0.0: programs that read the JSON look up its keys by name, so new names break them. A breaking change raises MAJOR and resets the other two.

(d) (a) under ### Fixed, (b) under ### Added, and (c) under ### Changed, with an entry that says plainly what breaks.

(e)

git tag -a v3.3.0 -m "rainkit 3.3.0"
git push origin v3.3.0

-a makes an annotated tag, with its author, date, and message. git push alone doesn’t send tags.

Question 19 (LO-8.4, 4 points)

For each task, choose a list, a tuple, a dictionary, or a set, and give the reason in a few words. (1 point each)

(a) The names of the stations already seen while reading a large file, to skip repeats.

(b) A station’s location, a latitude and a longitude, used as a key in a dictionary.

(c) Each station’s total rainfall, looked up by the station’s name.

(d) One day’s readings, in the order they arrived, with new ones added at the end.

Answer

(a) A set: in checks a set quickly however large it grows, and a set holds each name once.

(b) A tuple: it can’t change, so it can be a dictionary key, and its two positions have fixed meanings.

(c) A dictionary: it maps each name to its total, and finds a name quickly.

(d) A list: it keeps the order, allows repeats, and append adds to the end.

Question 20 (LO-11.4, 5 points)

(a) (3 points) Write a recursive function count_numbers(data) that returns how many numbers (int or float) are in data, at any depth of lists and dictionaries. Count a dictionary’s values, not its keys. Strings count as 0. (The data holds no True or False.)

(b) (1 point) What does it return for this?

station = {
    "name": "Harbor",
    "location": [51.5, -0.1],
    "readings": [
        {"day": "2026-11-02", "rain_mm": 1.2, "temps": [8.5, 11]},
        {"day": "2026-11-03", "rain_mm": 0.0, "temps": []},
    ],
}

(c) (1 point) Name your function’s base case or cases.

Answer

(a)

def count_numbers(data):
    """Return how many numbers are in data, at any depth of lists and dictionaries."""
    if isinstance(data, dict):
        return sum(count_numbers(value) for value in data.values())
    if isinstance(data, list):
        return sum(count_numbers(item) for item in data)
    if isinstance(data, (int, float)):
        return 1
    return 0

One point for each of the three cases: a dictionary, a list, and anything else. A loop that adds up the recursive calls is as good as sum.

(b) 6: 51.5, -0.1, 1.2, 8.5, 11, and 0.0. An empty list counts 0.

(c) Anything that is neither a dictionary nor a list: a number returns 1, and anything else, such as a string, returns 0, without another call. Every call goes one level deeper, so the calls reach a base case.

After the self-test

Add up your points. If you lost points on a question, its objective IDs name the modules to review: reread each one’s summary and redo its practice exercises, which are on the page beside its reading. Then go on to the release of your capstone project.