Objectives: LO-3.1, LO-3.2, LO-3.3
Prerequisites: the Module 3 reading and
Lab 2
Time: about 2 hours
In this lab you predict the value of conditions, write scripts that choose what to print, repair
two decisions that go wrong without any error message, and write tests that find the mistakes
hiding at a decision’s boundaries. As before, each exercise ends with a check cell that prints
passed or says what is wrong, and fails until you answer.
Setup¶
Run the next cell first. It prints the version of Python, makes the scratch folder, and
defines Lab 2’s helpers: run_script(path, typed=...) runs a script with the text a user would
type and shows its output, and output_of(path, typed=...) returns that output for a check.
import os
import subprocess
import sys
print("Python", sys.version.split()[0])
os.makedirs("scratch", exist_ok=True)
# Runs a script, showing each line of typed input after its prompt, as a terminal does.
RUNNER = r"""
import builtins, os, sys, traceback
path = sys.argv[1]
sys.argv = sys.argv[1:]
sys.path[0] = os.path.dirname(os.path.abspath(path))
real_input = builtins.input
def input(prompt=""):
text = real_input(prompt)
print(text)
return text
builtins.input = input
source = open(path, encoding="utf-8").read()
try:
exec(compile(source, path, "exec"), {"__name__": "__main__", "__file__": path})
except SystemExit:
raise
except BaseException as error:
traceback.print_exception(type(error), error, error.__traceback__.tb_next)
sys.exit(1)
"""
def run_script(path, typed=""):
"""Run a Python file as the terminal would, with typed input, and show what it prints."""
result = subprocess.run(
[sys.executable, "-c", RUNNER, path], input=typed, capture_output=True, text=True
)
print(result.stdout, end="")
print(result.stderr, end="", file=sys.stderr)
def output_of(path, typed=""):
"""Run a Python file with typed input, and return what it printed, errors included."""
result = subprocess.run(
[sys.executable, "-c", RUNNER, path], input=typed, capture_output=True, text=True
)
return result.stdout + result.stderr1. Comparisons and Boolean expressions¶
Run the next cell, then change the two strings and run it again. Try "apple" and "Apple",
then "10" and "9", then "cat" and "cats".
first = "apple"
second = "banana"
print(first < second, first == second, first > second)Exercise L3.1 (LO-3.1, ★, about 10 minutes)¶
Predict whether each expression is True or False, without running it, and write True
or False (no quotes) after each name.
| Name | Expression |
|---|---|
b1 | 7 > 3 and 2 > 5 |
b2 | not 7 > 3 or 2 < 5 |
b3 | 3 < 5 < 4 |
b4 | "Zebra" < "apple" |
b5 | 10 == 10.0 |
b6 | "10" == 10 |
b7 | 5 >= 5 and not 5 > 5 |
b8 | 0.1 + 0.2 == 0.3 |
Hint
not applies only to the comparison right after it, because comparisons run first. Capital letters come before lowercase ones.
b1 = ...
b2 = ...
b3 = ...
b4 = ...
b5 = ...
b6 = ...
b7 = ...
b8 = ...predictions = [b1, b2, b3, b4, b5, b6, b7, b8]
values = [7 > 3 and 2 > 5, not 7 > 3 or 2 < 5, 3 < 5 < 4, "Zebra" < "apple", 10 == 10.0,
"10" == 10, 5 >= 5 and not 5 > 5, 0.1 + 0.2 == 0.3]
wrong = [f"b{n}" for n in range(1, 9) if predictions[n - 1] is not values[n - 1]]
assert not wrong, "These predictions are wrong, or aren't True or False: " + ", ".join(wrong)
print("passed")Exercise L3.2 (LO-3.1, ★, about 10 minutes)¶
For each value, predict whether Python treats it as true or as false in an if. Write True
if it counts as true, and False if it counts as false.
| Name | Value |
|---|---|
t1 | 0 |
t2 | "0" |
t3 | "" |
t4 | " " |
t5 | -1 |
t6 | 0.0 |
t7 | "False" |
t8 | None |
t1 = ...
t2 = ...
t3 = ...
t4 = ...
t5 = ...
t6 = ...
t7 = ...
t8 = ...predictions = [t1, t2, t3, t4, t5, t6, t7, t8]
values = [0, "0", "", " ", -1, 0.0, "False", None]
wrong = [f"t{n}" for n in range(1, 9) if predictions[n - 1] is not bool(values[n - 1])]
assert not wrong, "These predictions are wrong, or aren't True or False: " + ", ".join(wrong)
print("passed")Check any you got wrong with bool, in the next cell: change the value and run it.
bool("0")2. if, else, and elif¶
Run the next cell. Then change temperature to 30, 29, 20, 19, 10, 9, and -5, predicting the
word before each run. Which values sit on a boundary?
temperature = 24
if temperature >= 30:
print("hot")
elif temperature >= 20:
print("warm")
elif temperature >= 10:
print("mild")
else:
print("cold")Exercise L3.3 (LO-3.2, ★, about 15 minutes)¶
Write a script, scratch/parity.py, that asks for a whole number with the prompt Number: and
says whether it is even or odd. With 7 typed, it prints:
Number: 7
7 is oddThe check also types 8, 0, and -3.
Hint
A number is even when the remainder after dividing it by 2 is 0.
%%writefile scratch/parity.py
number = int(input("Number: "))run_script("scratch/parity.py", typed="7\n")for typed, word in [(7, "odd"), (8, "even"), (0, "even"), (-3, "odd")]:
expected = f"Number: {typed}\n{typed} is {word}\n"
actual = output_of("scratch/parity.py", typed=f"{typed}\n")
assert actual == expected, f"With {typed} typed, expected:\n{expected}\nbut got:\n{actual}"
print("passed")Exercise L3.4 (LO-3.2, ★★, about 15 minutes)¶
A course grades a score out of 100: 85 or more is a distinction, 70 to 84 a merit, 50 to 69 a
pass, and below 50 a fail. The script below is meant to print the grade, but it prints Pass
for a score of 90. Run it with a few scores, work out why, and fix it, without adding and or
chained comparisons: change only the order and the conditions.
Hint
Which condition is true for 90? Python runs the first true branch and skips the rest.
%%writefile scratch/grade.py
score = int(input("Score: "))
if score >= 50:
print("Pass")
elif score >= 70:
print("Merit")
elif score >= 85:
print("Distinction")
else:
print("Fail")run_script("scratch/grade.py", typed="90\n")cases = [(0, "Fail"), (49, "Fail"), (50, "Pass"), (69, "Pass"), (70, "Merit"), (84, "Merit"),
(85, "Distinction"), (100, "Distinction")]
for typed, grade in cases:
expected = f"Score: {typed}\n{grade}\n"
actual = output_of("scratch/grade.py", typed=f"{typed}\n")
assert actual == expected, f"With {typed} typed, expected:\n{expected}\nbut got:\n{actual}"
source = open("scratch/grade.py", encoding="utf-8").read()
assert " and " not in source and "<" not in source, "Change only the order and the conditions."
print("passed")Exercise L3.5 (LO-3.1, LO-3.2, ★★, about 10 minutes)¶
This script should continue only when the user types yes or y. Run it with no typed: it
continues anyway. Fix the condition.
%%writefile scratch/proceed.py
answer = input("Continue? ")
if answer == "yes" or "y":
print("Continuing")
else:
print("Stopping")run_script("scratch/proceed.py", typed="no\n")cases = [("yes", "Continuing"), ("y", "Continuing"), ("no", "Stopping"), ("n", "Stopping"),
("", "Stopping"), ("Yes please", "Stopping")]
for typed, word in cases:
expected = f"Continue? {typed}\n{word}\n"
actual = output_of("scratch/proceed.py", typed=f"{typed}\n")
assert actual == expected, f"With {typed!r} typed, expected:\n{expected}\nbut got:\n{actual}"
print("passed")3. Testing a decision¶
A cinema charges 5.00 for a child under 13, 9.50 for an adult from 13 to 64, and 6.00 for a senior of 65 or over. The next cell saves a script that prints the right ticket.
%%writefile scratch/ticket.py
age = int(input("Age: "))
if age < 13:
print("Child ticket: 5.00")
elif age < 65:
print("Adult ticket: 9.50")
else:
print("Senior ticket: 6.00")Exercise L3.6 (LO-3.3, ★, about 5 minutes)¶
The ticket changes at two boundaries. Name the last age on each side of each one.
oldest_child = ...
youngest_adult = ...
oldest_adult = ...
youngest_senior = ...assert (oldest_child, youngest_adult) == (12, 13), "Under 13 is a child, and 13 is an adult."
assert (oldest_adult, youngest_senior) == (64, 65), "65 or over is a senior."
print("passed")The next cell defines a helper for testing the script. ticket_for(30) runs the script named by
TICKET_SCRIPT with 30 typed, and returns the line it printed, so one test is one assert:
assert ticket_for(30) == "Adult ticket: 9.50"TICKET_SCRIPT = "scratch/ticket.py"
def ticket_for(age):
"""Run the ticket script with this age typed, and return the last line it printed."""
return output_of(TICKET_SCRIPT, typed=f"{age}\n").splitlines()[-1]
print(ticket_for(30))Exercise L3.7 (LO-3.3, ★★, about 20 minutes)¶
Write tests for the ticket script in the next cell: one assert per test, each comparing
ticket_for(...) with the line you expect. Reach every branch, and test both sides of both
boundaries. One test is there to start you off. Run the cell: every test should pass, because
the script is right.
Then run the check straight after your test cell. It runs your tests again on four versions of the script, each with one mistake at a boundary, and passes only if your tests catch all four. A test that can’t fail when the program is wrong tells you nothing.
Hint
The reading’s car park example used six tests for two boundaries. Your answers to Exercise L3.6 are four of them.
assert ticket_for(30) == "Adult ticket: 9.50"
print("all tests passed")tests = In[-2] # The cell you ran just before this one.
assert "assert" in tests and "ticket_for" in tests, (
"Run your test cell, then run this check straight after it."
)
exec(tests) # Your tests must pass on the correct script.
mistakes = {
"age <= 13 (a 13-year-old pays as a child)": ("age < 13", "age <= 13"),
"age < 12 (a 12-year-old pays as an adult)": ("age < 13", "age < 12"),
"age <= 65 (a 65-year-old pays as an adult)": ("age < 65", "age <= 65"),
"age < 64 (a 64-year-old pays as a senior)": ("age < 65", "age < 64"),
}
correct = open("scratch/ticket.py", encoding="utf-8").read()
missed = []
for mistake, (old, new) in mistakes.items():
with open("scratch/ticket_mistake.py", "w", encoding="utf-8") as file:
file.write(correct.replace(old, new))
TICKET_SCRIPT = "scratch/ticket_mistake.py"
try:
exec(tests)
missed.append(mistake)
except AssertionError:
pass
finally:
TICKET_SCRIPT = "scratch/ticket.py"
assert not missed, "Your tests pass even with these mistakes: " + "; ".join(missed)
print("passed")4. Putting it together¶
Exercise L3.8 (LO-3.2, ★★★, about 25 minutes)¶
A year is a leap year if it divides by 4, except that a year that divides by 100 is not, unless it also divides by 400. So 2024 is a leap year, 2023 isn’t, 1900 isn’t (it divides by 100 but not by 400), and 2000 is.
Write a script, scratch/leap.py, that asks for a year with the prompt Year: and prints
either 2024 is a leap year or 2023 is not a leap year. The check types 2024, 2023, 1900,
2000, 2100, and 2400. You may use if, elif, and else, or one condition built with and
and or.
Hint 1
“Divides by 4” is year % 4 == 0.
Hint 2
Check the narrowest rule first: divides by 400, then divides by 100, then divides by 4.
%%writefile scratch/leap.py
year = int(input("Year: "))run_script("scratch/leap.py", typed="1900\n")cases = [(2024, True), (2023, False), (1900, False), (2000, True), (2100, False), (2400, True)]
for typed, leap in cases:
line = f"{typed} is a leap year" if leap else f"{typed} is not a leap year"
expected = f"Year: {typed}\n{line}\n"
actual = output_of("scratch/leap.py", typed=f"{typed}\n")
assert actual == expected, f"With {typed} typed, expected:\n{expected}\nbut got:\n{actual}"
print("passed")Summary¶
In this lab you:
predicted comparisons, Boolean expressions, and which values count as true;
wrote scripts that choose with
if,elif, andelse;fixed a chain whose order made branches unreachable, and the
ormistake;named a decision’s boundaries, and wrote tests that catch mistakes at each one; and
turned a rule with exceptions, the leap year, into a decision.
Next, the Module 3 practice gives you more exercises with answers, and Module 4 makes programs repeat themselves with loops.