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¶
In the terminal, in
py101, make a folder for this module and move into it:mkdir m09 cd m09The prompt now ends with
m09.In VS Code, create
greet.pyin them09folder, with the code from the reading, and save it.Run it, with an argument and then without one:
python greet.py Ada python greet.pyThe first prints
['greet.py', 'Ada']andHello, Ada!. The second prints['greet.py']and stops withIndexError: list index out of range, naming line 4.Press the Up arrow twice to bring back the first command, change
Adato"Ada Lovelace", and press Enter. It printsHello, 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.
Make a folder
datainsidem09, and move into it.Show the folder you are in.
Go back to
py101with onecdcommand.List what
py101holds.
Answer
mkdir data
cd data
pwd
cd ../..
lspwd 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.
python args.py one twopython args.py "one two"python args.py 3 4.5 -1
Answer
0 args.py,1 one,2 two, and2 arguments.0 args.py,1 one two, and1 arguments: the quotes make one argument, and the shell removes them.0 args.py,1 3,2 4.5,3 -1, and3 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: himain.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: 12Without --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.
python dice.py --sides 20 --rolls 2 --seed 9python dice.py --sides 1python dice.py --rolls twopython dice.py -h
Answer
Rolls: [15, 20]andTotal: 35, with status 0.The usage line and
dice.py: error: --sides must be at least 2, with status 2.The usage line and
dice.py: error: argument --rolls: invalid int value: 'two', with status 2.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.
The start is a positional argument, a whole number from 1 to 100; anything else stops with an error and status 2.
--wordchanges the last line:python countdown.py 2 --word Launchprints2,1, andLaunch!.--stepcounts down by more than 1, and its default is 1:python countdown.py 10 --step 4prints10,6,2, andGo!. A step below 1 stops with an error.
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).
Today’s date.
The number of days in February 2028.
Waiting two seconds before the next line runs.
A random password, safe enough to use for real.
The middle value of a list of numbers.
Answer
datetime.date.today().calendar.monthrange(2028, 2), which returns the weekday of the first day and the number of days; its second item is29, because 2028 is a leap year.calendar.isleap(2028)isTrue.time.sleep(2).The
secretsmodule, for examplesecrets.token_urlsafe(16). Therandommodule’s page warns that its numbers mustn’t be used for security.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:
In
py101, make a folderwordtooland move into it.Create a virtual environment named
.venvinwordtool, with the Python you installed (pythonon Windows,python3on macOS and Linux).With the new environment’s Python, install pytest, pinned to 9.2.0.
List the new environment’s packages.
Write
requirements.txt, by hand in VS Code, so that it installs pytest 9.2.0.Delete
wordtool/.venvin VS Code’s Explorer, and rebuild it fromrequirements.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 listOn 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.0After 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.