Objectives: LO-1.1, LO-1.2, LO-1.3
Prerequisites: the Module 1 reading
Time: about 2 hours
In this lab you run Python in notebook cells, write script files and run them, print a receipt
that Python works out for you, and fix programs that stop with an error. Each exercise ends with
a check cell. Run it after your answer: it prints passed, or it stops with a message that
says what is wrong. Until you answer an exercise, its check fails on purpose.
Run the cells in order, from the top, by clicking in each one and pressing Shift+Enter. If you change an earlier cell, run it again before the cells after it.
Setup¶
Run the next cell first. It prints the version of Python that runs this lab, which should be
3.12 or newer, and makes a folder named scratch beside the lab for the files you write.
It also defines two helpers, small pieces of code that the rest of the lab uses:
run_script runs a script file the way the terminal would and shows what it prints, and
output_of gives a check cell the script’s output to compare. You don’t need to understand
their code yet; Module 5 teaches you to write your own. Nothing in this lab is random, so it
needs no random seed.
import os
import subprocess
import sys
print("Python", sys.version.split()[0])
os.makedirs("scratch", exist_ok=True)
def run_script(path):
"""Run a Python file as the terminal would, and show what it prints."""
result = subprocess.run([sys.executable, path], capture_output=True, text=True)
print(result.stdout, end="")
print(result.stderr, end="", file=sys.stderr)
def output_of(path):
"""Run a Python file, and return what it printed, error messages included."""
result = subprocess.run([sys.executable, path], capture_output=True, text=True)
return result.stdout + result.stderr1. Running code in cells¶
Run the next cell. It holds two print lines, so it shows two lines of output.
print("Hello!")
print(2 + 3)The next cell has no print. Before you run it, predict what it shows. Then run it.
7 / 2
6 / 2A notebook cell shows the value of its last line only, so you saw 3.0 and not 3.5. A
script would show neither, because a script shows only what it prints.
Exercise L1.1 (LO-1.1, ★, about 10 minutes)¶
For each of the three snippets below, decide what it shows when it is run as a script, and what it shows when it is the whole of one notebook cell. Don’t run them first; predict.
Snippet A:
print(4 * 5)Snippet B:
4 * 5Snippet C: two lines,
4 * 5and thenprint(4 + 5)
Write each answer as text between the quotes, as the lines in the next cell show. Write 20,
9, or nothing. The lines that start with a name and = give each answer a name, so the
check cell can read it; Module 2 explains them properly.
Hint
A script shows only what print shows. A notebook cell shows what print shows, and also the value of its last line if that line is a calculation.
script_a = "..."
script_b = "..."
script_c = "..."
cell_a = "..."
cell_b = "..."
cell_c = "..."assert script_a == "20" and cell_a == "20", "Snippet A prints, and print works the same everywhere."
assert script_b == "nothing", "A script shows only what print shows, and snippet B has no print."
assert cell_b == "20", "A notebook cell shows the value of its last line when it's a calculation."
assert script_c == "9", "The script throws 4 * 5 away and prints 4 + 5."
assert cell_c == "9", "The cell's last line is a print, so the cell shows only what it prints."
print("passed")2. Writing and running a script¶
A cell that starts with %%writefile doesn’t run its code: it saves the rest of the cell as a
file. The next cell saves a script named hello.py in the scratch folder, and the cell after it
runs that script, as the terminal would. Run both.
%%writefile scratch/hello.py
print("Hello!")
2 + 3
print("Goodbye!")run_script("scratch/hello.py")The middle line worked out 5, but the script threw it away, so the script printed two lines.
Exercise L1.2 (LO-1.1, LO-1.2, ★, about 10 minutes)¶
Change the %%writefile cell below so that the script scratch/intro.py prints exactly these
three lines:
Hello, world!
This is my first script.
2 + 2 = 4The 4 on the third line must come from Python adding 2 + 2, not from typing 4 inside a
string. Run the cell to save the file, then run the run_script cell after it to see the output,
then run the check.
Hint
print puts a space between the things you give it, separated by commas. The third line is a string, "2 + 2 =", followed by a calculation.
%%writefile scratch/intro.py
print("Hello, world!")run_script("scratch/intro.py")expected = "Hello, world!\nThis is my first script.\n2 + 2 = 4\n"
assert output_of("scratch/intro.py") == expected, (
"The output doesn't match the three lines exactly. Compare spelling, capital letters, "
"punctuation, and spaces."
)
source = open("scratch/intro.py", encoding="utf-8").read()
assert "2+2)" in source.replace(" ", ""), (
"Let Python work out 2 + 2: put the calculation outside the quotes."
)
print("passed")Now run the same script two other ways, outside the notebook:
In VS Code, open
scratch/intro.py(it’s in yourpy101folder, insidescratch), and click Run Python File, the triangle in the top-right corner.In VS Code’s terminal, in your
py101folder, run it by typing the path to Python and then the path to the file:.venv\Scripts\python scratch\intro.pyon Windows, or.venv/bin/python scratch/intro.pyon macOS and Linux.
Both should print the same three lines as the cell above.
3. Printing a receipt¶
A bakery sells tea at 1.80 a cup and muffins at 2.40 each. The script below should print a receipt for 2 cups of tea and 3 muffins, with Python doing every calculation.
Exercise L1.3 (LO-1.2, ★, about 15 minutes)¶
Finish the script so that it prints exactly these lines:
Bakery receipt
2 teas at 1.80: 3.6
3 muffins at 2.40: 7.199999999999999
Total: 10.799999999999999Yes, Python really prints 7.199999999999999 for 3 * 2.40: computers store most decimal
numbers very slightly wrong, and Module 2 explains why and how to print 7.20 instead. For now,
let Python print what it works out.
Start the script with a comment that says what it does. Write each amount as a calculation, such
as 2 * 1.80, never as a number you worked out yourself. The fourth line is empty.
Hint 1
print() with nothing between the parentheses prints an empty line.
Hint 2
The total is the cost of the teas plus the cost of the muffins: 2 * 1.80 + 3 * 2.40. Python multiplies before it adds, so this needs no parentheses.
%%writefile scratch/receipt.py
print("Bakery receipt")run_script("scratch/receipt.py")expected = (
"Bakery receipt\n"
"2 teas at 1.80: 3.6\n"
"3 muffins at 2.40: 7.199999999999999\n"
"\n"
"Total: 10.799999999999999\n"
)
assert output_of("scratch/receipt.py") == expected, (
"The output doesn't match the five lines exactly. Check each line, the empty fourth line, and "
"that every amount is a calculation."
)
source = open("scratch/receipt.py", encoding="utf-8").read()
assert source.lstrip().startswith("#"), "Start the script with a comment that says what it does."
assert "10.79" not in source and "7.19" not in source and "3.6" not in source, (
"Write each amount as a calculation, such as 2 * 1.80, not as a number you worked out."
)
print("passed")4. The order of operations¶
Three readings of a river’s depth were 120, 135, and 150 centimeters. The next cell tries to print their average. Run it, and decide whether the answer is reasonable.
print(120 + 135 + 150 / 3)Exercise L1.4 (LO-1.2, ★, about 5 minutes)¶
An average must lie between the smallest and the largest reading, and 305.0 doesn’t. Write the
correct calculation after average = in the next cell, so that it gives 135.0.
average = 120 + 135 + 150 / 3assert average == 135.0, f"Your calculation gives {average}, not 135.0. Which operation runs first?"
print("passed")5. Reading error messages¶
Each of the next three scripts stops with an error. For each one, run the %%writefile cell and
the run_script cell, and read the error message from the bottom up: what kind of error is it,
and which line does it name? Then fix the script, save it again, and run it again.
Exercise L1.5 (LO-1.3, ★, about 10 minutes)¶
Run the next two cells, read the error, and fix the script so that it prints
Welcome to the course! and then Let's begin. Then fill in the kind of error the original
script had and the line number its message named.
%%writefile scratch/welcome.py
print("Welcome to the course!")
print("Let's begin.)run_script("scratch/welcome.py")kind = "..."
line = 0assert output_of("scratch/welcome.py") == "Welcome to the course!\nLet's begin.\n", (
"The script doesn't print the two lines yet. Did you add the missing closing quote?"
)
assert kind == "SyntaxError", "Copy the kind of error from the last line of the message."
assert line == 2, "Which line number does the message name?"
print("passed")Notice that the original script printed nothing at all, not even its first line. Python reads the whole file before it runs any of it, so a syntax error stops every line.
Exercise L1.6 (LO-1.3, ★, about 10 minutes)¶
This script is meant to print the number of minutes in a week. Run it, read the error, fix the script, and fill in the kind of error and the line number.
%%writefile scratch/week.py
print("Minutes in a day:", 24 * 60)
Print("Minutes in a week:", 7 * 24 * 60)run_script("scratch/week.py")kind = "..."
line = 0assert output_of("scratch/week.py") == "Minutes in a day: 1440\nMinutes in a week: 10080\n", (
"The script doesn't print both lines yet."
)
assert kind == "NameError", "Copy the kind of error from the last line of the message."
assert line == 2, "Which line number does the message name?"
print("passed")This time the first line printed before the error. Unlike a syntax error, a name error stops the script only when Python reaches the line that has it.
Exercise L1.7 (LO-1.3, ★★, about 10 minutes)¶
This script is meant to print Seconds in an hour: 3600. Run it, read the error, and fix the
script without typing 3600 yourself: keep the calculation. Then fill in the kind of error
and the line number.
Hint
+ can’t join a string and a number. print can show both if you give it them separately.
%%writefile scratch/hour.py
# Prints how many seconds there are in one hour.
print("Seconds in an hour: " + 60 * 60)run_script("scratch/hour.py")kind = "..."
line = 0assert output_of("scratch/hour.py") == "Seconds in an hour: 3600\n", (
"The script doesn't print the line yet. Check the space after the colon too: print adds one "
"between the things you give it."
)
source = open("scratch/hour.py", encoding="utf-8").read()
assert "3600" not in source, "Keep the calculation 60 * 60 in the script."
assert kind == "TypeError", "Copy the kind of error from the last line of the message."
assert line == 2, "Which line number does the message name? (The comment is line 1.)"
print("passed")Exercise L1.8 (LO-1.3, ★★, about 15 minutes)¶
This script has two mistakes. Fix them one at a time: run it, fix the error the message names, and run it again until it prints these two lines:
Days in a leap year: 366
Hours in a leap year: 8784Then answer: which error did Python report first? Write its kind.
%%writefile scratch/leap.py
print("Days in a leap year:", 365 + 1)
pritn("Hours in a leap year:", (365 + 1) * 24run_script("scratch/leap.py")first_kind = "..."assert output_of("scratch/leap.py") == "Days in a leap year: 366\nHours in a leap year: 8784\n", (
"The script should print exactly the two lines. Fix one error at a time, and run it again."
)
assert first_kind == "SyntaxError", (
"Python reads the whole file before running any of it, so which kind of error does it find "
"first?"
)
print("passed")6. The interactive interpreter¶
The last way to run Python is the interactive interpreter. It can’t run inside a notebook, so
this part has no check cell. In VS Code’s terminal, in your py101 folder:
Start the interpreter:
.venv\Scripts\pythonon Windows, or.venv/bin/pythonon macOS and Linux. Python prints its version, then the>>>prompt.Type
7 / 2and press Enter, then2 + 3 * 4, then(2 + 3) * 4. Python shows each value withoutprint.Type
prnt("hi")and read the error message. The interpreter shows the same kinds of error as a script, then gives you the prompt back.Type
exit()to leave.
Summary¶
In this lab you:
saw that a notebook cell shows the value of its last line, and a script only what it prints;
wrote scripts and ran them from the notebook, from VS Code, and from the terminal;
let Python do a receipt’s arithmetic, and used parentheses to fix an average;
read error messages from the bottom up, and fixed a syntax error, a name error, and a type error; and
saw that a syntax error stops a whole script, while other errors stop it at their own line.
Next, the Module 1 practice gives you more exercises with answers, and Module 2 explains the values, the variables, and the strange decimals you met in this lab.