Objectives: LO-2.1, LO-2.2, LO-2.3, LO-2.4
Prerequisites: the Module 2 reading and Lab 1
Time: about 2 hours
In this lab you predict what expressions give before Python works them out, trace variables,
write scripts that read what the user types, find the bug that a missing conversion causes, and
print numbers the way people expect to read them. As in Lab 1, each exercise ends with a check
cell that prints passed or says what is wrong, and fails until you answer.
Run the cells in order, from the top, with Shift+Enter.
Setup¶
Run the next cell first. It prints the version of Python, makes the scratch folder, and
defines the two helpers from Lab 1, with one addition: both now take the text a user would type.
run_script("scratch/age.py", typed="30\n") runs the script as if a user typed 30 and pressed
Enter (\n stands for pressing Enter). Every time the script calls input, it reads the next
typed line. The helper shows the typed text after the prompt, as a terminal does, so the output
looks the way it would if you ran the script yourself. If a script asks for more lines than
typed holds, it stops with an EOFError (“end of file”), meaning it ran out of input.
import math
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. Types and operators¶
type names the type of any value. Run the cell, then change the value inside type( ) to
7 // 2, then 7.0 // 2, then "7" * 2, and run it after each change.
print(type(7 / 2), 7 / 2)// and % split a quantity into whole units and what is left over. Change minutes to 59,
60, 61, and 1,000 (typed as 1000, without the comma), and run the cell each time.
minutes = 135
print(minutes // 60, "hours and", minutes % 60, "minutes")Exercise L2.1 (LO-2.1, ★, about 15 minutes)¶
Predict the value of each expression, without running it, and write your prediction the way
Python would show the value: a whole number for an int (4), a number with a decimal point
for a float (4.0), and text in quotes for a str ("4"). The type counts: 4 and 4.0
are different answers.
| Name | Expression |
|---|---|
p1 | 9 / 3 |
p2 | 9 // 4 |
p3 | 9 % 4 |
p4 | 9.0 // 4 |
p5 | 2 + 3 * 4 ** 2 |
p6 | -3 ** 2 |
p7 | "3" + "4" |
p8 | "ab" * 2 + "c" |
Then run the check. It lists every prediction that differs from Python’s value; work out why before you change it.
Hint
/ always gives a float. ** runs before *, and before a minus sign in front of a number. + and * on strings join and repeat them.
p1 = ...
p2 = ...
p3 = ...
p4 = ...
p5 = ...
p6 = ...
p7 = ...
p8 = ...predictions = [p1, p2, p3, p4, p5, p6, p7, p8]
values = [9 / 3, 9 // 4, 9 % 4, 9.0 // 4, 2 + 3 * 4 ** 2, -3 ** 2, "3" + "4", "ab" * 2 + "c"]
wrong = []
for number, (guess, value) in enumerate(zip(predictions, values), start=1):
if type(guess) is not type(value) or guess != value:
wrong.append(f"p{number}")
assert not wrong, "These predictions differ from Python's value or type: " + ", ".join(wrong)
print("passed")2. Variables¶
Exercise L2.2 (LO-2.2, ★, about 10 minutes)¶
Trace this program on paper, in a table with a column for each variable and a row for each line, as the reading does. Then write the final value of each variable in the next cell.
a = 2
b = a + 3
a = b * 2
c = a - b
b = b + cOnce the check passes, paste the program into Python Tutor and step through it, comparing each step with your table.
final_a = ...
final_b = ...
final_c = ...assert final_c == 5, "c is worked out on line 4, from the values a and b have at that moment."
assert final_a == 10, "Line 3 changes a, using b's value from line 2."
assert final_b == 10, "Line 5 uses b's old value on the right, then changes b."
print("passed")The next cell tries to swap the values of two variables, so that left refers to "coffee"
and right to "tea". Predict what it prints, then run it.
left = "tea"
right = "coffee"
left = right
right = left
print(left, right)Both names end up referring to "coffee". The third line moved left’s arrow to "coffee",
and after that nothing referred to "tea" any more, so the fourth line had nothing to copy.
Exercise L2.3 (LO-2.2, ★★, about 10 minutes)¶
Below the first two lines of the next cell, add lines that swap the values of left and
right. Use a third variable, named temp, to keep one value safe while you move the other.
Don’t type "tea" or "coffee" again: the swap must work whatever the two values are.
Hint
Think of swapping the drinks in two cups with a third, empty cup. Pour one drink into the empty cup first.
left = "tea"
right = "coffee"assert left == "coffee" and right == "tea", f"left is {left!r} and right is {right!r}."
assert "temp" in globals(), "Use a third variable, named temp."
assert temp == "tea", "Keep left's first value in temp before you change left."
print("passed")Python also has a one-line swap, left, right = right, left, which Module 7 explains.
3. Reading input¶
The next cell saves a script that reads a name and greets the user, and the cell after it runs
the script with Ada typed in. Run both, then change typed to your own name and run it again.
%%writefile scratch/greet.py
name = input("What's your name? ")
print("Hello,", name)run_script("scratch/greet.py", typed="Ada\n")Now run the same script in VS Code’s terminal, where you type the name yourself:
.venv\Scripts\python scratch\greet.py on Windows, or .venv/bin/python scratch/greet.py on
macOS and Linux.
Exercise L2.4 (LO-2.3, ★, about 15 minutes)¶
Write a script, scratch/hours.py, that asks for a number of minutes with the prompt
Minutes: and prints it in hours and minutes. With 135 typed, it prints exactly:
Minutes: 135
135 minutes is 2 hours and 15 minutesThe first line is the prompt with the typed text, which the helper shows; your script prints
only the second. The check also types 60, 59, and 0.
Hint 1
input gives a string. Convert it with int before you use // and %.
Hint 2
Give print five things: the minutes, the text "minutes is", the hours, the text "hours and", and so on. print puts the spaces between them.
%%writefile scratch/hours.py
minutes = input("Minutes: ")run_script("scratch/hours.py", typed="135\n")for typed, hours, left_over in [(135, 2, 15), (60, 1, 0), (59, 0, 59), (0, 0, 0)]:
expected = f"Minutes: {typed}\n{typed} minutes is {hours} hours and {left_over} minutes\n"
actual = output_of("scratch/hours.py", typed=f"{typed}\n")
assert actual == expected, f"With {typed} typed, expected:\n{expected}\nbut got:\n{actual}"
print("passed")Exercise L2.5 (LO-2.3, ★, about 10 minutes)¶
This script stops with an error when the user types 30. Run it and read the message. Then fix
the script so that it prints Next year you will be 31, and fill in the kind of error the
original script had.
%%writefile scratch/age.py
age = input("How old are you? ")
print("Next year you will be", age + 1)run_script("scratch/age.py", typed="30\n")kind = "..."assert output_of("scratch/age.py", typed="30\n") == (
"How old are you? 30\nNext year you will be 31\n"
), "The script doesn't print the right lines yet. What type does input give back?"
assert output_of("scratch/age.py", typed="7\n").endswith("be 8\n"), "Try it with 7 typed too."
assert kind == "TypeError", "Copy the kind of error from the last line of the message."
print("passed")Exercise L2.6 (LO-2.3, ★★, about 15 minutes)¶
This script adds two prices. Run it: it prints a total without any error, but the total is
wrong. Work out why, then fix the script so that it prints Total: 3.75 for these prices.
Hint
What does + do with two strings? Prices can have a decimal point, so which conversion do they need?
%%writefile scratch/prices.py
# Adds the prices of two items.
first = input("First price: ")
second = input("Second price: ")
print("Total:", first + second)run_script("scratch/prices.py", typed="2.50\n1.25\n")assert output_of("scratch/prices.py", typed="2.50\n1.25\n").endswith("Total: 3.75\n"), (
"With 2.50 and 1.25 typed, the last line should be Total: 3.75."
)
assert output_of("scratch/prices.py", typed="10\n5\n").endswith("Total: 15.0\n"), (
"With 10 and 5 typed, the last line should be Total: 15.0. Did you convert with float?"
)
print("passed")This bug is more dangerous than the one in Exercise L2.5, because nothing tells you it is there. Only running the program with inputs whose answer you already know shows it.
4. Formatting with f-strings¶
Run the next cell, then change the format specification after the colon to .1f, .3f, ,.2f,
>12.2f, and .0%, and run it after each change. The square brackets show where the spaces go.
amount = 1234.5678
print(f"[{amount:.2f}]")Exercise L2.7 (LO-2.4, ★★, about 15 minutes)¶
A shop sells pens at 1.15 each, notebooks at 3.40 each, and erasers at 0.65 each. Write a
script, scratch/shop.py, that prints a receipt for 4 pens, 2 notebooks, and 1 eraser,
exactly like this:
Pens 4.60
Notebooks 6.80
Eraser 0.65
Total 12.05Each label is 12 characters wide, lined up on the left, and each amount 8 characters wide, lined up on the right, with two decimals. Let Python work out every amount, and use f-strings for the layout, not spaces you type yourself.
Hint 1
The reading’s worked example “a receipt that lines up” does the same with widths 10 and 8.
Hint 2
Store each amount in a variable first, such as pens = 4 * 1.15. Then the total is the sum of three variables, and each print holds one f-string.
%%writefile scratch/shop.py
# Prints a receipt for 4 pens, 2 notebooks, and 1 eraser.run_script("scratch/shop.py")expected = (
"Pens 4.60\n"
"Notebooks 6.80\n"
"Eraser 0.65\n"
"Total 12.05\n"
)
assert output_of("scratch/shop.py") == expected, (
"The output doesn't match the receipt exactly. Check each width and the number of decimals."
)
source = open("scratch/shop.py", encoding="utf-8").read()
assert "12.05" not in source and "4.60" not in source and "6.80" not in source, (
"Let Python work out the amounts and format them, rather than typing them."
)
assert "8.2f" in source and ("<12" in source or ":12}" in source), (
"Use format specifications such as :<12 and :>8.2f for the layout, rather than typing spaces."
)
print("passed")The format only changes how a number is shown. Print the unformatted total in the next cell,
and see why the receipt needed .2f.
print(4 * 1.15 + 2 * 3.40 + 0.65)5. Floats are approximate¶
Run the next cell. Then change 0.6 to 0.6000000000000001 and run it again.
total = 0.1 + 0.2 + 0.3
print(total, total == 0.6, math.isclose(total, 0.6))Exercise L2.8 (LO-2.4, ★★, about 15 minutes)¶
Set
equalto an expression that comparestotalwith0.6the right way for floats, so that it isTrue.Predict the values of
round(0.5),round(1.5),round(2.5), andround(3.5), without running them, and write them asr1tor4.Predict
round(2.675, 2), and write it asr5.
Hint
The reading’s section “Rounding” gives the rule for halves, and why 2.675 isn’t really a half.
equal = ...
r1 = ...
r2 = ...
r3 = ...
r4 = ...
r5 = ...assert equal is True, "Use math.isclose(total, 0.6), which is True; total == 0.6 is False."
assert [r1, r2, r3, r4] == [0, 2, 2, 4], "round sends a half to the even neighbor: 0, 2, 2, 4."
assert all(type(r) is int for r in [r1, r2, r3, r4]), "round(x) with no second value gives an int."
assert r5 == 2.67, "The float stored for 2.675 is slightly below 2.675, so it rounds down."
print("passed")The messages in that check give the answers away once you run it, so make your predictions first: a wrong prediction you then understand teaches you more than a right one you copied.
6. Putting it together¶
Exercise L2.9 (LO-2.3, LO-2.4, ★★, about 20 minutes)¶
Write a script, scratch/convert.py, that asks for a temperature in Celsius with the prompt
Celsius: , converts it to Fahrenheit with , and prints both with one
decimal. With 21 typed, it prints:
Celsius: 21
21.0 C = 69.8 FTemperatures can have decimals, such as 37.5. Write the whole script yourself; the check types
21, -40, 37.5, and 100.
%%writefile scratch/convert.py
# Converts a temperature from Celsius to Fahrenheit.run_script("scratch/convert.py", typed="21\n")cases = [("21", "21.0 C = 69.8 F"), ("-40", "-40.0 C = -40.0 F"), ("37.5", "37.5 C = 99.5 F"),
("100", "100.0 C = 212.0 F")]
for typed, line in cases:
expected = f"Celsius: {typed}\n{line}\n"
actual = output_of("scratch/convert.py", typed=typed + "\n")
assert actual == expected, f"With {typed} typed, expected:\n{expected}\nbut got:\n{actual}"
print("passed")Summary¶
In this lab you:
predicted the type and value of expressions with
/,//,%,**, and strings;traced variables, and swapped two of them with a third;
wrote scripts that read input, converted it with
intandfloat, and found the error and the silent wrong answer that a missing conversion causes;lined up a receipt with f-strings and format specifications; and
compared floats with
math.isclose, and saw howroundtreats halves.
Next, the Module 2 practice gives you more exercises with answers, and Module 3
shows how a program makes decisions with the True and False you met here.