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-9.1–9.5, LO-10.1–10.4, LO-11.1–11.4, LO-12.1–12.4, and LO-13.1–13.4, and, revisited, LO-5.3, LO-6.2, LO-7.3, LO-8.1, and LO-8.2
Prerequisites: Modules 1–13
Time: 2 hours for the 18 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 so far, most of them on Modules 9–13: scripts and the command line, Git, files, errors, and tests. It isn’t graded. Take it after Module 13 and before you start Project 2, 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-11.2 belongs to Module 11. Run the question’s code to see the answer for yourself.

Rules for your answers

Questions

Question 1 (LO-9.1, LO-9.3, 5 points)

A terminal is open in py101, which holds this:

py101/
├── .venv/
└── m09/
    ├── count.py
    └── data/
        └── names.txt

count.py is:

"""Count the lines in a file."""

import argparse


def main():
    parser = argparse.ArgumentParser(description="Count the lines in a file.")
    parser.add_argument("path", help="the file to count")
    parser.add_argument("--min", type=int, default=0, help="count only lines this long or longer")
    args = parser.parse_args()
    if args.min < 0:
        parser.error("--min can't be negative")
    with open(args.path, encoding="utf-8") as file:
        lines = [line for line in file if len(line.strip()) >= args.min]
    print(len(lines))


if __name__ == "__main__":
    main()

(a) (1 point) Write the commands that move into m09 and run count.py on names.txt with the course environment’s Python.

(b) (4 points) From m09, what happens with each of these, and what exit status does each end with? Write python for the environment’s Python.

  1. python count.py data/names.txt --min two

  2. python count.py

  3. python count.py data/names.txt --min -1

  4. python count.py data/missing.txt

Answer

(a) On macOS and Linux:

cd m09
../.venv/bin/python count.py data/names.txt

On Windows, cd m09, then ..\.venv\Scripts\python count.py data\names.txt. The environment’s Python is one folder up, so its path starts with ...

(b) One point each, for what happens and the status together. Lines that start with $ are the commands:

$ python count.py data/names.txt --min two
usage: count.py [-h] [--min MIN] path
count.py: error: argument --min: invalid int value: 'two'
$ python count.py
usage: count.py [-h] [--min MIN] path
count.py: error: the following arguments are required: path
$ python count.py data/names.txt --min -1
usage: count.py [-h] [--min MIN] path
count.py: error: --min can't be negative

The first three end with status 2: argparse reports its own errors, and the one from parser.error, with the usage line and a message, and exits with 2. The fourth stops with a traceback that ends FileNotFoundError: [Errno 2] No such file or directory: 'data/missing.txt', and an uncaught exception ends with status 1. A common mistake is to expect -1 to be read as an option: argparse takes it as the value of --min, because it looks like a negative number.

Question 2 (LO-9.2, 5 points)

units.py and trip.py are in the same folder:

print("loading units")


def km_to_miles(km):
    return km * 0.621371


print(km_to_miles(10))
import units

print("trip:", round(units.km_to_miles(42.195), 1))

(a) (2 points) What does python trip.py print?

(b) (3 points) Rewrite units.py so that python units.py still prints both of its lines, but import units prints nothing.

Answer

(a) Importing units runs all of units.py, so its two lines come first:

loading units
6.21371
trip: 26.2

One point for the two lines from units.py, and one for the last line.

(b) Put the lines that should run only as a script under a main guard:

def km_to_miles(km):
    return km * 0.621371


if __name__ == "__main__":
    print("loading units")
    print(km_to_miles(10))

When Python runs units.py as a script, __name__ is "__main__"; when another file imports it, __name__ is "units", and the guarded lines don’t run. One point for the if line, one for moving both print calls under it, and one for keeping km_to_miles outside it, where importers can use it.

Question 3 (LO-9.4, 5 points)

(a) (4 points) Name a standard-library module and the function, or the operation, that does each job:

  1. Choose one item at random from a list.

  2. Find the number of days between two dates.

  3. Find the middle value of a list of numbers.

  4. Round a number up to the next whole number, such as 3.2 to 4.

(b) (1 point) After from datetime import date, what is (date(2026, 12, 25) - date(2026, 12, 4)).days?

Answer

(a) One point each: random.choice; datetime, subtracting one date from another and reading the result’s .days; statistics.median; and math.ceil. Other correct choices earn the point, such as random.sample(items, 1) for the first.

(b) 21. Subtracting two dates gives a timedelta, a length of time, whose .days is the whole number of days.

Question 4 (LO-9.5, 5 points)

(a) (2 points) Put these steps in order, to set up a new project that uses pytest 9.2.0 and to record what it needs: install pytest 9.2.0 with the environment’s pip; create a virtual environment named .venv; write pytest==9.2.0 in requirements.txt; add .venv/ to .gitignore.

(b) (1 point) A teammate clones your repository and creates their own .venv. What one command installs everything the project needs?

(c) (2 points) You run python -m pip install requests, with no path in front of python, and then .venv/bin/python fetch.py stops with ModuleNotFoundError: No module named 'requests'. Why, and what should you have typed?

Answer

(a) Create the environment, then install pytest 9.2.0 into it, with the environment’s own Python. Writing requirements.txt and adding .venv/ to .gitignore can come in either order, as long as both come before your next commit. Two points for an order that works, one if a single step is out of place.

(b) .venv/bin/python -m pip install -r requirements.txt on macOS and Linux, or .venv\Scripts\python -m pip install -r requirements.txt on Windows.

(c) python without a path ran some other Python, whose pip installed requests into that Python’s own environment. Each environment has its own packages, so the project’s .venv still doesn’t have it. Type .venv/bin/python -m pip install requests (or the Windows path). One point for the reason, one for the command.

Question 5 (LO-10.1, LO-10.2, 6 points)

In a new repository, you run these steps in order:

git init
# Write dice.py and notes.txt.
git add dice.py
git commit -m "Add a dice roller"
# Change dice.py, and let the program write debug.log.
git add dice.py
# Change dice.py again.
git status

(a) (2 points) What does git status report about dice.py, notes.txt, and debug.log?

(b) (1 point) If you ran git commit -m "..." now, which version of dice.py would it record?

(c) (1 point) Write one line for .gitignore that keeps debug.log, and every other file whose name ends in .log, out of the repository.

(d) (2 points) Write a commit message, a summary line and a body, for this change: --sides now rejects values below 2 with an error, because 0 sides made random.randint crash.

Answer

(a) dice.py appears twice: under “Changes to be committed”, as modified, for the first change, and under “Changes not staged for commit”, as modified, for the second. notes.txt and debug.log are under “Untracked files”, because neither was ever added. One point for dice.py in both places, one for the two untracked files.

(b) The version from the first change, the one in the staging area. The second change stays in the working folder until you git add it again.

(c) *.log.

(d) For example:

Reject --sides below 2 with an error

With 0 sides, random.randint(1, 0) crashed with a ValueError.
Now argparse reports the problem and exits with status 2.

One point for a summary line in the imperative mood (“Reject”, not “Rejected”) that says what changed, and one for a body that says why.

Question 6 (LO-10.4, 5 points)

Choose the Git commands for each situation, and say why.

(a) (1 point) You changed dice.py and saved it, but haven’t staged it, and you want the last committed version back.

(b) (2 points) A commit that you pushed to GitHub yesterday broke the game. You want to undo it, and other people may already have it.

(c) (2 points) You want to try a new scoring rule without disturbing main, and keep it only if it works.

Answer

(a) git restore dice.py, which replaces the file with its last committed version. The changes are lost, so be sure first.

(b) git revert and the commit’s hash, from git log, then git push. revert adds a new commit that undoes the old one, so the history that others already have stays the same, and nobody’s copy breaks. One point for the command, one for the reason.

(c) git switch -c new-scoring to make a branch and move to it, then commit the change there. If it works, git switch main and git merge new-scoring; if not, switch back to main and leave the branch unmerged. One point for working on a branch, one for merging into main only after checking.

Question 7 (LO-11.1, LO-6.2, 5 points)

from pathlib import Path

p = Path("data") / "2026" / "readings.csv"

(a) (3 points) Give p.name, p.stem, p.suffix, and p.parent.name.

(b) (1 point) Why build the path with / and Path, instead of writing "data/2026/readings.csv" as one string?

(c) (1 point) A file saved as UTF-8 holds the word Zürich. What does Path("city.txt").read_text(encoding="cp1252") return?

Answer

(a) 'readings.csv', 'readings', '.csv', and '2026'. Three points for all four, two for three of them, one for two.

(b) Path joins the parts with the separator of the operating system the program runs on, \ on Windows and / elsewhere, and gives the parts back by name, so the code works everywhere and needn’t take strings apart.

(c) 'Zürich'. UTF-8 stores ü as two bytes, and cp1252 reads each byte as a character of its own.

Question 8 (LO-11.2, LO-8.1, 7 points)

rain.csv holds:

station,date,rain_mm
Harbor,2026-11-02,2.4
Hilltop,2026-11-02,
Harbor,2026-11-03,12.0
Hilltop,2026-11-03,0.6

Write rain_by_station(path), which returns a dictionary of each station’s total rain, as a float, skipping fields that are empty. For this file, it returns {'Harbor': 14.4, 'Hilltop': 0.6}.

Answer
import csv


def rain_by_station(path):
    """Return each station's total rain in mm, from a CSV file; skip empty rain_mm fields."""
    totals = {}
    with open(path, newline="", encoding="utf-8") as file:
        for row in csv.DictReader(file):
            if row["rain_mm"] == "":
                continue
            station = row["station"]
            totals[station] = totals.get(station, 0) + float(row["rain_mm"])
    return totals

Two points for reading the rows with csv.DictReader and with, one for newline="" and the encoding, one for skipping the empty field, two for adding each value to its station’s total with get (or an if that starts a new total), and one for converting with float. Common mistakes: adding the strings, which joins them; and float(""), which raises ValueError.

Question 9 (LO-11.3, LO-8.2, 5 points)

What does this print?

import json

data = {"station": "Harbor", "readings": (8.5, 11.0), "ok": True, "note": None, 3: "three"}
text = json.dumps(data)
print(text)
back = json.loads(text)
print(back == data, back["readings"], list(back))
Answer
{"station": "Harbor", "readings": [8.5, 11.0], "ok": true, "note": null, "3": "three"}
False [8.5, 11.0] ['station', 'readings', 'ok', 'note', '3']

Three points for the first line: one for the tuple becoming a list, one for true and null, and one for the key 3 becoming the string "3". Two points for the second: the dictionaries differ, because the tuple came back as a list and the key as a string, so back == data is False. JSON has no tuples, and its keys are always strings.

Question 10 (LO-11.4, LO-8.2, 7 points)

Write a recursive function total_numbers(data) that returns the total of every number in data made of nested lists and dictionaries, and ignores strings. In a dictionary, count its values, not its keys. Then name its base cases.

print(total_numbers({"a": [1, 2, {"b": 3.5}], "c": "text", "d": []}))
print(total_numbers([]))
print(total_numbers(7))
6.5
0
7
Answer
def total_numbers(data):
    """Return the total of every number in nested lists and dictionaries."""
    if isinstance(data, (int, float)):
        return data
    total = 0
    if isinstance(data, list):
        for item in data:
            total = total + total_numbers(item)
    elif isinstance(data, dict):
        for value in data.values():
            total = total + total_numbers(value)
    return total

The base cases are a number, which is its own total, and anything that is neither a list nor a dictionary, such as a string, whose total is 0. An empty list or dictionary also gives 0 without a recursive call, because its loop doesn’t run. Two points for the number case, two for the recursive calls on list items and on dictionary values, one for ignoring strings, and two for naming the base cases.

Question 11 (LO-12.1, 6 points)

report.py imports stats.py. Running python report.py prints this:

Harbor: 8.7
Traceback (most recent call last):
  File ".../py101/m12/report.py", line 17, in <module>
    main()
    ~~~~^^
  File ".../py101/m12/report.py", line 14, in main
    print_report(["Harbor", "Hiltop"])
    ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
  File ".../py101/m12/report.py", line 10, in print_report
    print(f"{name}: {stats.station_mean(READINGS, name):.1f}")
                     ~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
  File ".../py101/m12/stats.py", line 6, in station_mean
    temps = readings[name]
            ~~~~~~~~^^^^^^
KeyError: 'Hiltop'

(a) (2 points) What is the exception, and what does its message mean?

(b) (1 point) Which file and line raised it?

(c) (1 point) Give the chain of calls, from the first frame to the last.

(d) (2 points) In which file would you fix the bug, and why there?

Answer

(a) KeyError: the dictionary readings has no key 'Hiltop'. One point for the exception, one for the meaning.

(b) stats.py, line 6.

(c) The script’s own code (<module>), then main, then print_report, then station_mean.

(d) In report.py, line 14: the station’s name is misspelled there, "Hiltop" for "Hilltop". The last frame shows where Python noticed the problem, not always where the mistake is; reading up the chain finds where the bad value came from. One point for the file, one for the reason.

Question 12 (LO-12.2, LO-7.3, 6 points)

(a) (4 points) What does this print?

def to_number(text):
    try:
        value = float(text)
    except ValueError:
        print("bad:", text)
        return None
    else:
        print("ok:", value)
        return value
    finally:
        print("checked", text)


results = [to_number(t) for t in ["2.5", "x", " 3 "]]
print(results)

(b) (2 points) Why would except Exception: be a worse choice than except ValueError: here? Give a call that shows the difference.

Answer

(a)

ok: 2.5
checked 2.5
bad: x
checked x
ok: 3.0
checked  3 
[2.5, None, 3.0]

The last checked line has two spaces in the middle and one at the end, from " 3 ", which float accepts. One point for each pair of lines for the three calls, with finally printing after else or except even though they return, and one for the list.

(b) except Exception also catches the exceptions that come from bugs. to_number(None) makes float raise TypeError, which except ValueError lets through, so the mistake shows at once; except Exception would print bad: None and carry on. One point for the reason, one for an example.

Question 13 (LO-12.3, LO-5.3, 5 points)

(a) (3 points) Write parse_percent(text), which returns a percentage written as text, such as "45%", as a number, 45.0. It raises ValueError with a message that says what was wrong for text that doesn’t end with %, and for a percentage outside 0 to 100. Give it a docstring.

(b) (2 points) find_station(stations, name) looks up a station that a user typed, and may not find it. Should it raise an exception or return None when the name isn’t there? Explain.

Answer

(a)

def parse_percent(text):
    """Return a percentage such as "45%" as a number from 0 to 100."""
    if not text.endswith("%"):
        raise ValueError(f"expected a percentage such as 45%, got {text!r}")
    value = float(text[:-1])
    if not 0 <= value <= 100:
        raise ValueError(f"percentage out of range 0 to 100: {text!r}")
    return value

One point for each check with a clear message, and one for the conversion and the docstring. Text such as "abc%" raises the ValueError that float raises, which says what was wrong too.

(b) Either can be right, if the docstring says which. Returning None suits a name that is often missing for ordinary reasons, such as a typo, because the caller expects to check for it and ask again. Raising suits a name that should always be there, because a None that the caller forgot to check would fail later, far from the cause. Two points for a choice and a reason of this kind.

Question 14 (LO-12.4, 5 points)

This function should return the length of the longest run of equal values in a row, but longest_run([3, 3, 1, 2, 2, 2]) gives 2 instead of 3.

def longest_run(values):
    """Return the length of the longest run of equal values in a row."""
    longest = 0
    current = 0
    previous = None
    for value in values:
        if value == previous:
            current = current + 1
        else:
            longest = max(longest, current)
            current = 1
        previous = value
    return longest

(a) (1 point) Shrink the input: give the shortest list for which it gives a wrong answer.

(b) (2 points) Form a hypothesis about the cause, and give an input that tests it: one that should give the right answer if the hypothesis is true, and one that shouldn’t.

(c) (2 points) Fix the function.

Answer

(a) [1], which gives 0 instead of 1. (The empty list gives 0, which is right.)

(b) “The last run is never compared with longest, because longest changes only when a new run starts.” If that’s true, [1, 1, 2] gives the right answer, 2, because its longest run ends before the list does, while [2, 1, 1] gives 1 instead of 2, because its longest run is the last one. Both are what the function gives. One point for the hypothesis, one for the test.

(c) Compare the last run too, after the loop: return max(longest, current). Then longest_run([3, 3, 1, 2, 2, 2]) is 3, [1] gives 1, and [] still gives 0.

Question 15 (LO-13.1, 8 points)

Write pytest tests for parse_percent from Question 13, in a file that imports it with from percent import parse_percent. Use one parametrized test for the text it accepts, with a typical case and both edges, and one parametrized test for the text it refuses, with a case for each way it can refuse. Use match in the second.

Answer
import pytest

from percent import parse_percent


@pytest.mark.parametrize(
    "text, expected",
    [
        ("45%", 45),
        ("12.5%", 12.5),
        ("0%", 0),
        ("100%", 100),
    ],
)
def test_parse_percent(text, expected):
    assert parse_percent(text) == expected


@pytest.mark.parametrize(
    "text, message",
    [
        ("45", "expected a percentage"),
        ("101%", "out of range"),
        ("-1%", "out of range"),
        ("abc%", "could not convert"),
    ],
)
def test_bad_percent_raises(text, message):
    with pytest.raises(ValueError, match=message):
        parse_percent(text)

All eight pass. Two points for the imports and the two parametrize decorators, two for the typical case and both edges (0 and 100), two for the error cases (no %, and outside the range on either side), and two for pytest.raises(ValueError, match=...). == is safe here, because float returns these values exactly, with no arithmetic; pytest.approx is right too. The case for "abc%" is a bonus: the function doesn’t promise its message.

Question 16 (LO-13.1, LO-13.2, 6 points)

percent.py holds the parse_percent from Question 13. Predict the result of python -m pytest test_percent_more.py, with this file saved as test_percent_more.py:

import pytest

from percent import parse_percent


@pytest.fixture
def samples():
    return ["45%", "0%", "100%"]


@pytest.mark.parametrize("text", ["5%", "50%", "500%"])
def test_in_range(text):
    assert 0 <= parse_percent(text) <= 100


def test_samples(samples):
    for text in samples:
        assert parse_percent(text) >= 0


def test_third(samples):
    assert parse_percent("33.3%") / 100 == 0.333


def percent_check():
    assert parse_percent("1%") == 1


def test_missing_sign():
    with pytest.raises(TypeError):
        parse_percent("45")

(a) (3 points) How many tests does pytest collect, and how many pass and fail?

(b) (1 point) Which function never runs, and why?

(c) (2 points) Fix test_third and test_missing_sign, so that they pass and still test what they mean to.

Answer

(a) Six collected, three passed, three failed:

collected 6 items
=========================== short test summary info ============================
FAILED test_percent_more.py::test_in_range[500%] - ValueError: percentage out...
FAILED test_percent_more.py::test_third - AssertionError: assert (33.3 / 100)...
FAILED test_percent_more.py::test_missing_sign - ValueError: expected a perce...
========================= 3 failed, 3 passed in 0.04s ==========================

The parametrized test counts as three tests, and "500%" raises ValueError, which fails it. One point each for the three numbers.

(b) percent_check: its name doesn’t start with test, so pytest doesn’t collect it.

(c) assert parse_percent("33.3%") / 100 == pytest.approx(0.333), because 33.3 / 100 is 0.33299999999999996 as a float. pytest.raises(ValueError, match="expected a percentage"), because the function raises ValueError, not TypeError. One point each. (test_third also asks for samples without using it, which does no harm but is worth removing.)

Question 17 (LO-13.2, LO-13.3, 5 points)

(a) (2 points) Before you fix longest_run from Question 14, write the test that captures its bug. Include a case that already gives the right answer.

(b) (1 point) What do you expect to see when you run it before the fix, and after?

(c) (2 points) save_settings(path, settings) writes a dictionary to a JSON file. Write a test for it that never touches your real files.

Answer

(a)

import pytest

from runs import longest_run


@pytest.mark.parametrize(
    "values, expected",
    [
        ([3, 3, 1, 2, 2, 2], 3),
        ([1], 1),
        ([2, 1, 1], 2),
        ([1, 1, 2], 2),
        ([], 0),
    ],
)
def test_longest_run(values, expected):
    assert longest_run(values) == expected

One point for the failing cases from the bug report and Question 14, one for a case that already passes, such as [1, 1, 2] or [].

(b) Before the fix, the three cases that end with the longest run fail, and two pass: 3 failed, 2 passed. After it, all five pass. Seeing the failures first proves that the test catches the bug.

(c) For example:

import json

from settings import save_settings


def test_save_settings_writes_json(tmp_path):
    path = tmp_path / "settings.json"
    save_settings(path, {"units": "metric", "days": 7})
    assert json.loads(path.read_text(encoding="utf-8")) == {"units": "metric", "days": 7}

One point for using tmp_path, which gives the test a new, empty folder, and one for checking what the file holds.

Question 18 (LO-13.4, 4 points)

A project’s workflow runs python -m pip install -r requirements.txt and then python -m pytest on every push. Its requirements.txt holds only pytest==9.2.0. Your tests pass on your computer, where you also installed matplotlib, and one test file imports it.

(a) (2 points) After you push, which step fails, and what does its log show?

(b) (1 point) What happens to the steps after it?

(c) (1 point) How do you fix it?

Answer

(a) Run the tests fails: the runner installed only pytest, so importing the test file stops with ModuleNotFoundError: No module named 'matplotlib', which pytest reports as an error while collecting, and pytest ends with status 2. One point for the step, one for the error.

(b) They’re skipped: a failed step stops the job.

(c) Add matplotlib to requirements.txt, pinned to the version you have, commit, and push.

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 Project 2.