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.

These exercises practice what the Module 9 reading explained. They aren’t graded. Unlike earlier practice, most of them happen in a real terminal: open your py101 folder in VS Code, and open a terminal with Terminal > New Terminal. Write your answer or your prediction first, then run the commands to check it. The answers are in the collapsed blocks; open one only after you have an answer of your own.

The commands use python for your environment’s Python. From the m09 folder, type ..\.venv\Scripts\python on Windows and ../.venv/bin/python on macOS and Linux in its place, as the reading explains.

Worked example: a script with an argument, in the terminal

  1. In the terminal, in py101, make a folder for this module and move into it:

    mkdir m09
    cd m09

    The prompt now ends with m09.

  2. In VS Code, create greet.py in the m09 folder, with the code from the reading, and save it.

  3. Run it, with an argument and then without one:

    python greet.py Ada
    python greet.py

    The first prints ['greet.py', 'Ada'] and Hello, Ada!. The second prints ['greet.py'] and stops with IndexError: list index out of range, naming line 4.

  4. Press the Up arrow twice to bring back the first command, change Ada to "Ada Lovelace", and press Enter. It prints Hello, Ada Lovelace!, because the quotes make one argument.

Exercise 9.1 (LO-9.1, ★, about 10 minutes)

Your terminal is in py101/m09. Write the commands that do each step, then run them.

  1. Make a folder data inside m09, and move into it.

  2. Show the folder you are in.

  3. Go back to py101 with one cd command.

  4. List what py101 holds.

Answer
mkdir data
cd data
pwd
cd ../..
ls

pwd ends with py101/m09/data (with \ on Windows). cd ../.. goes up twice: to m09, then to py101. ls lists .venv (on macOS and Linux, only with ls -a, because names that start with a dot are hidden there), your labs, and m09.

Exercise 9.2 (LO-9.1, ★★, about 15 minutes)

Save this as args.py in m09:

import sys

for position, argument in enumerate(sys.argv):
    print(position, argument)
print(len(sys.argv) - 1, "arguments")

Predict what each command prints, then run it.

  1. python args.py one two

  2. python args.py "one two"

  3. python args.py 3 4.5 -1

Answer
  1. 0 args.py, 1 one, 2 two, and 2 arguments.

  2. 0 args.py, 1 one two, and 1 arguments: the quotes make one argument, and the shell removes them.

  3. 0 args.py, 1 3, 2 4.5, 3 -1, and 3 arguments. They print like numbers, but they are the strings "3", "4.5", and "-1".

sys.argv[0] is the script’s name as you typed it. Run python ../m09/args.py from m09, and it’s ../m09/args.py.

Worked example: a module that runs once

Save these three files in m09:

a.py:

print("loading a")
GREETING = "hi"

b.py:

import a

print("loading b")

main.py:

import a
import b

print("main:", a.GREETING)

python main.py prints:

loading a
loading b
main: hi

main.py imports a, which runs a.py and prints loading a. Then it imports b, which runs b.py; b.py imports a too, but Python has already loaded a, so it doesn’t run it again. A module runs once per program, however many files import it.

Exercise 9.3 (LO-9.2, ★★, about 15 minutes)

This script works out a tip and splits a bill:

bill = float(input("Bill: "))
percent = float(input("Tip percent: "))
people = int(input("People: "))
tip = bill * percent / 100
share = (bill + tip) / people
print(f"Tip {tip:.2f}, each pays {share:.2f}")

Split it into a module, billmath.py, with two functions, tip_amount(bill, percent) and share_per_person(bill, tip, people), and a script, split.py, that imports them, asks the three questions, and prints the line. Give split.py a main guard, and give billmath.py a test of each function that runs only when you run it as a script.

Hint

billmath.py holds no input and no print outside its main guard, so importing it does nothing but define the functions.

Answer

billmath.py:

"""Arithmetic for splitting a bill."""


def tip_amount(bill, percent):
    """Return the tip on bill at percent percent."""
    return bill * percent / 100


def share_per_person(bill, tip, people):
    """Return what each of people pays for bill plus tip."""
    return (bill + tip) / people


if __name__ == "__main__":
    assert tip_amount(80, 15) == 12
    assert share_per_person(80, 12, 4) == 23
    print("billmath tests passed")

split.py:

"""Ask for a bill, a tip, and a number of people, and print each share."""

from billmath import share_per_person, tip_amount


def main():
    bill = float(input("Bill: "))
    percent = float(input("Tip percent: "))
    people = int(input("People: "))
    tip = tip_amount(bill, percent)
    print(f"Tip {tip:.2f}, each pays {share_per_person(bill, tip, people):.2f}")


if __name__ == "__main__":
    main()

With 80, 15, and 4, split.py prints Tip 12.00, each pays 23.00. The two tests compare floats with ==, which is safe here because 12 and 23 come out exact; math.isclose is the safe habit for other values.

Worked example: a tool with options

This tool rolls dice. --seed has no default, so it is None when the user leaves it out, and the program seeds random only when the user gives one:

"""Roll dice and print each roll and the total."""

import argparse
import random


def roll(sides, rolls):
    """Return a list of rolls random numbers from 1 to sides."""
    results = []
    for _ in range(rolls):
        results.append(random.randint(1, sides))
    return results


def main():
    parser = argparse.ArgumentParser(description="Roll dice.")
    parser.add_argument("--sides", type=int, default=6, help="sides on each die (default 6)")
    parser.add_argument("--rolls", type=int, default=1, help="how many dice to roll (default 1)")
    parser.add_argument("--seed", type=int, help="a seed, to repeat a run")
    args = parser.parse_args()
    if args.sides < 2:
        parser.error("--sides must be at least 2")
    if args.rolls < 1:
        parser.error("--rolls must be at least 1")
    if args.seed is not None:
        random.seed(args.seed)
    results = roll(args.sides, args.rolls)
    print("Rolls:", results)
    print("Total:", sum(results))


if __name__ == "__main__":
    main()

Saved as dice.py, python dice.py --rolls 3 --seed 9 prints the same lines on every run with the course’s Python:

Rolls: [4, 5, 3]
Total: 12

Without --seed, each run rolls differently. Project 1 asks for a --seed option for this reason: a game you can repeat is a game you can test.

Exercise 9.4 (LO-9.3, ★★, about 15 minutes)

With dice.py saved in m09, predict what each command does, including its exit status, then run it. Check the status with echo $? on macOS and Linux, or $LASTEXITCODE in PowerShell, straight after each command.

  1. python dice.py --sides 20 --rolls 2 --seed 9

  2. python dice.py --sides 1

  3. python dice.py --rolls two

  4. python dice.py -h

Answer
  1. Rolls: [15, 20] and Total: 35, with status 0.

  2. The usage line and dice.py: error: --sides must be at least 2, with status 2.

  3. The usage line and dice.py: error: argument --rolls: invalid int value: 'two', with status 2.

  4. The help, which lists the three options with their help texts and -h, with status 0.

Exercise 9.5 (LO-9.3, ★★★, about 25 minutes)

Write countdown.py, a tool that counts down from a number: python countdown.py 3 prints 3, 2, 1, and Go!, one per line.

Put the counting in a function, countdown_lines(start, step, word), that returns the list of lines, so that it can be tested without running the program.

Hint

range(start, 0, -step) counts down from start and stops before 0.

Answer
"""Count down from a number, then print a word."""

import argparse


def countdown_lines(start, step, word):
    """Return the lines of a countdown from start by step, ending with word and "!"."""
    lines = []
    for number in range(start, 0, -step):
        lines.append(str(number))
    lines.append(word + "!")
    return lines


def main():
    parser = argparse.ArgumentParser(description="Count down from a number.")
    parser.add_argument("start", type=int, help="the number to start from, 1 to 100")
    parser.add_argument("--step", type=int, default=1, help="how much to count down by")
    parser.add_argument("--word", default="Go", help="the word to end with (default Go)")
    args = parser.parse_args()
    if args.start < 1 or args.start > 100:
        parser.error("start must be from 1 to 100")
    if args.step < 1:
        parser.error("--step must be at least 1")
    for line in countdown_lines(args.start, args.step, args.word):
        print(line)


if __name__ == "__main__":
    main()

countdown_lines(10, 4, "Go") is ["10", "6", "2", "Go!"]. An option with no type stays a string, as --word does. Testing start and step in main and leaving countdown_lines to count keeps the function simple to test with assert.

Exercise 9.6 (LO-9.4, ★★, about 15 minutes)

Find a module and a function in the standard library for each task, using the library reference, and try each one in the interactive interpreter (python with no script).

  1. Today’s date.

  2. The number of days in February 2028.

  3. Waiting two seconds before the next line runs.

  4. A random password, safe enough to use for real.

  5. The middle value of a list of numbers.

Answer
  1. datetime.date.today().

  2. calendar.monthrange(2028, 2), which returns the weekday of the first day and the number of days; its second item is 29, because 2028 is a leap year. calendar.isleap(2028) is True.

  3. time.sleep(2).

  4. The secrets module, for example secrets.token_urlsafe(16). The random module’s page warns that its numbers mustn’t be used for security.

  5. statistics.median.

Searching the reference’s contents page for a word from the task (“calendar”, “sleep”, “password”) finds each module. Other answers that the reference supports are right too.

Exercise 9.7 (LO-9.5, ★★, about 25 minutes)

This exercise downloads a package, so it needs an internet connection. Set up a new project with its own environment:

  1. In py101, make a folder wordtool and move into it.

  2. Create a virtual environment named .venv in wordtool, with the Python you installed (python on Windows, python3 on macOS and Linux).

  3. With the new environment’s Python, install pytest, pinned to 9.2.0.

  4. List the new environment’s packages.

  5. Write requirements.txt, by hand in VS Code, so that it installs pytest 9.2.0.

  6. Delete wordtool/.venv in VS Code’s Explorer, and rebuild it from requirements.txt.

Answer

On macOS and Linux:

mkdir wordtool
cd wordtool
python3 -m venv .venv
.venv/bin/python -m pip install pytest==9.2.0
.venv/bin/python -m pip list

On Windows, use python -m venv .venv and .venv\Scripts\python in the last three commands.

The install ends with a line that starts Successfully installed and names pytest 9.2.0 and the packages it depends on: iniconfig, packaging, pluggy, and pygments, and on Windows also colorama. Their versions are the newest that pytest allows on the day you install. pip list shows them, and pip itself.

requirements.txt holds one line:

pytest==9.2.0

After deleting .venv, run the venv command again, then .venv/bin/python -m pip install -r requirements.txt, which installs the same pytest. The environment’s folder is disposable; requirements.txt is what you keep.