Objectives: LO-4.1, LO-4.2, LO-4.3, LO-4.4
Prerequisites: the Module 4 reading and Lab 3
Time: about 2 hours
In this lab you predict what range produces, stop a loop that never ends and fix one that
never starts, trace loops in tables, write each of the four loop patterns, count the passes of
nested loops, and finish with a number-guessing game. 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, sets the
random seed (section 6 explains it), and defines the helpers from Labs 2 and 3, with one change:
a script that runs for more than 5 seconds is stopped, with a message, so a loop that never ends
can’t freeze the notebook.
import os
import random
import subprocess
import sys
import time
print("Python", sys.version.split()[0])
os.makedirs("scratch", exist_ok=True)
random.seed(4)
TIME_LIMIT = 5 # seconds
STOPPED = f"(The script was still running after {TIME_LIMIT} seconds, so it was stopped.)\n"
# 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 output_of(path, typed=""):
"""Run a Python file with typed input, and return what it printed, errors included."""
try:
result = subprocess.run(
[sys.executable, "-c", RUNNER, path],
input=typed, capture_output=True, text=True, timeout=TIME_LIMIT,
)
except subprocess.TimeoutExpired:
return STOPPED
return result.stdout + result.stderr
def run_script(path, typed=""):
"""Run a Python file as the terminal would, with typed input, and show what it prints."""
print(output_of(path, typed), end="")1. range¶
Run the next cell, then change the values inside range( ) and run it again. Try range(5),
range(10, 0, -3), and range(4, 4).
for value in range(2, 12, 3):
print(value, end=" ")
print()Exercise L4.1 (LO-4.2, ★, about 10 minutes)¶
Predict, without running anything, how many times a for loop over each range runs, and the
last value of three of them.
| Name | Question |
|---|---|
n1 | How many times does a loop over range(7) run? |
n2 | How many times does a loop over range(3, 10) run? |
n3 | How many times does a loop over range(0, 20, 5) run? |
n4 | How many times does a loop over range(20, 0, -5) run? |
n5 | How many times does a loop over range(10, 3) run? |
last1 | What is the last value of range(3, 10)? |
last2 | What is the last value of range(0, 20, 5)? |
last3 | What is the last value of range(20, 0, -5)? |
Hint
The stop value is never included, even when counting down.
n1 = ...
n2 = ...
n3 = ...
n4 = ...
n5 = ...
last1 = ...
last2 = ...
last3 = ...answers = {"n1": n1, "n2": n2, "n3": n3, "n4": n4, "n5": n5,
"last1": last1, "last2": last2, "last3": last3}
right = {"n1": len(range(7)), "n2": len(range(3, 10)), "n3": len(range(0, 20, 5)),
"n4": len(range(20, 0, -5)), "n5": len(range(10, 3)), "last1": range(3, 10)[-1],
"last2": range(0, 20, 5)[-1], "last3": range(20, 0, -5)[-1]}
wrong = [name for name in answers if answers[name] != right[name]]
assert not wrong, "These predictions are wrong: " + ", ".join(wrong)
print("passed")2. Loops that never stop, and loops that never start¶
Exercise L4.2 (LO-4.1, ★, about 10 minutes)¶
This script should add up the numbers from 1 to 10 and print 55. Run the next two cells: the
script runs until the helper stops it. Find out why it never stops, and fix it.
Hint
Trace the first three passes. Does anything in the block change n?
%%writefile scratch/total.py
total = 0
n = 1
while n <= 10:
total = total + n
print(total)run_script("scratch/total.py")assert output_of("scratch/total.py") == "55\n", (
"The script should print 55. Each pass must move n toward the end of the loop."
)
print("passed")A loop that never ends in a cell of your own, rather than in a script, has no helper to stop it.
Click the Interrupt the kernel button (■) in the toolbar, or choose Kernel >
Interrupt Kernel. Try it on the next cell, a loop that waits a tenth of a second at a time:
run it, and interrupt it within 10 seconds. The cell stops with a KeyboardInterrupt. (So that
this lab can be checked automatically, this loop also ends by itself after 10 seconds.)
for tenth in range(100):
time.sleep(0.1)
print("The loop ended by itself. Run the cell again, and interrupt it this time.")Exercise L4.3 (LO-4.1, ★, about 5 minutes)¶
This script should count how many times 1 must be doubled to pass 1,000, and print
10 doublings reach 1024. Run it: the loop never runs. Fix the condition.
%%writefile scratch/doubling.py
amount = 1
doublings = 0
while amount > 1000:
amount = amount * 2
doublings = doublings + 1
print(doublings, "doublings reach", amount)run_script("scratch/doubling.py")assert output_of("scratch/doubling.py") == "10 doublings reach 1024\n", (
"A while condition says when to keep going, not when to stop."
)
print("passed")3. Tracing a loop¶
Exercise L4.4 (LO-4.3, ★, about 10 minutes)¶
Trace this loop on paper, with a row for each pass and a column for each of n, total, and
count. Then fill in the answers.
total = 0
count = 0
for n in range(2, 12, 3):
if n % 2 == 0:
total = total + n
count = count + 1passes: how many passes the loop makeslast_n: the value ofnafter the loopfinal_totalandfinal_count: the values oftotalandcountafter the loop
Once the check passes, step through the loop in Python Tutor.
passes = ...
last_n = ...
final_total = ...
final_count = ...assert passes == 4, "Write out the values of range(2, 12, 3): it starts at 2 and adds 3."
assert last_n == 11, "After the loop, n keeps its last value."
assert (final_total, final_count) == (10, 2), "Only the even values are added and counted."
print("passed")4. The four loop patterns¶
Exercise L4.5 (LO-4.3, ★, about 10 minutes)¶
Write a script, scratch/squares.py, that asks for a whole number n with the prompt n: ,
and adds up the squares of the numbers from 1 to n with an accumulator. With 4 typed, it
prints:
n: 4
Sum of squares from 1 to 4: 30(1 + 4 + 9 + 16 is 30.) The check also types 1, 3, and 10.
Hint
Start total at 0 before the loop. Which range gives 1 to n, including n?
%%writefile scratch/squares.py
n = int(input("n: "))run_script("scratch/squares.py", typed="4\n")for typed, total in [(4, 30), (1, 1), (3, 14), (10, 385)]:
expected = f"n: {typed}\nSum of squares from 1 to {typed}: {total}\n"
actual = output_of("scratch/squares.py", typed=f"{typed}\n")
assert actual == expected, f"With {typed} typed, expected:\n{expected}\nbut got:\n{actual}"
source = open("scratch/squares.py", encoding="utf-8").read()
assert "for" in source or "while" in source, "Use a loop to add up the squares."
print("passed")Exercise L4.6 (LO-4.2, LO-4.3, ★★, about 10 minutes)¶
Write a script, scratch/vowels.py, that asks for a line of text with the prompt Text: and
counts its vowels (a, e, i, o, and u, in either case) with a for loop over the string. With
Hello World typed, it prints:
Text: Hello World
Vowels: 3Hint
letter in "aeiouAEIOU" is True when letter is a vowel of either case.
%%writefile scratch/vowels.py
text = input("Text: ")run_script("scratch/vowels.py", typed="Hello World\n")cases = [("Hello World", 3), ("AEIOU aeiou", 10), ("rhythm", 0), ("Programming in Python", 5),
("", 0)]
for typed, vowels in cases:
expected = f"Text: {typed}\nVowels: {vowels}\n"
actual = output_of("scratch/vowels.py", typed=f"{typed}\n")
assert actual == expected, f"With {typed!r} typed, expected:\n{expected}\nbut got:\n{actual}"
print("passed")Exercise L4.7 (LO-4.3, ★★, about 15 minutes)¶
Write a script, scratch/factor.py, that asks for a whole number of 2 or more with the prompt
Number: , and searches for its smallest factor greater than 1: the first number from 2
upward that divides it with no remainder. Stop the search with break. With 91 typed, it
prints:
Number: 91
Smallest factor of 91: 7A prime number’s smallest factor is itself: 97 gives 97.
Hint
Loop over range(2, number + 1), and break when number % divisor == 0. After the loop, the loop variable holds the factor.
%%writefile scratch/factor.py
number = int(input("Number: "))run_script("scratch/factor.py", typed="91\n")for typed, factor in [(91, 7), (97, 97), (2, 2), (100, 2), (49, 7)]:
expected = f"Number: {typed}\nSmallest factor of {typed}: {factor}\n"
actual = output_of("scratch/factor.py", typed=f"{typed}\n")
assert actual == expected, f"With {typed} typed, expected:\n{expected}\nbut got:\n{actual}"
source = open("scratch/factor.py", encoding="utf-8").read()
assert "break" in source, "Stop the search with break once you find a factor."
print("passed")Exercise L4.8 (LO-4.3, ★★, about 15 minutes)¶
A board game takes 2 to 6 players. Write a script, scratch/players.py, that asks
Players (2-6): until the user types a number in that range, printing
Please enter 2 to 6. after each bad answer, and then prints the line below. With 1, 7, and
4 typed:
Players (2-6): 1
Please enter 2 to 6.
Players (2-6): 7
Please enter 2 to 6.
Players (2-6): 4
Starting a game for 4 players.Hint
Either ask once before a while loop whose condition describes a bad answer, and again inside it; or use while True: and break once the answer is good.
%%writefile scratch/players.py
players = int(input("Players (2-6): "))run_script("scratch/players.py", typed="1\n7\n4\n")for answers in [[1, 7, 4], [2], [6], [0, 10, -3, 5]]:
typed = "".join(f"{answer}\n" for answer in answers)
expected = ""
for answer in answers[:-1]:
expected += f"Players (2-6): {answer}\nPlease enter 2 to 6.\n"
expected += f"Players (2-6): {answers[-1]}\nStarting a game for {answers[-1]} players.\n"
actual = output_of("scratch/players.py", typed=typed)
assert actual == expected, f"Typing {answers}, expected:\n{expected}\nbut got:\n{actual}"
print("passed")5. Nested loops¶
Exercise L4.9 (LO-4.4, ★★, about 10 minutes)¶
For each pair of loops, predict how many times the inner block runs, without running it.
c1:
for a in range(4):
for b in range(5):
...c2:
for a in range(1, 5):
for b in range(a):
...c3:
for a in range(3):
for b in range(a, 3):
...Hint
When the inner range uses a, write down how many times the inner loop runs for each value of a, and add them up.
c1 = ...
c2 = ...
c3 = ...assert c1 == 20, "The inner range doesn't depend on a, so multiply the two counts."
assert c2 == 10, "The inner loop runs 1, 2, 3, then 4 times."
assert c3 == 6, "range(a, 3) has 3, then 2, then 1 values."
print("passed")Check your thinking with a counter. Change the loops in the next cell to each pair above, and run it.
runs = 0
for a in range(4):
for b in range(5):
runs = runs + 1
print(runs)Exercise L4.10 (LO-4.4, ★★, about 15 minutes)¶
Write a script, scratch/table.py, that asks for a size with the prompt Size: and prints a
multiplication table of that size, each product 4 characters wide. With 4 typed:
Size: 4
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16Hint
print(f"{row * column:4}", end="") prints one product without ending the line. A print() after the inner loop ends the row.
%%writefile scratch/table.py
size = int(input("Size: "))run_script("scratch/table.py", typed="4\n")for size in [4, 1, 6]:
rows = ""
for row in range(1, size + 1):
rows += "".join(f"{row * column:4}" for column in range(1, size + 1)) + "\n"
expected = f"Size: {size}\n{rows}"
actual = output_of("scratch/table.py", typed=f"{size}\n")
assert actual == expected, f"With {size} typed, expected:\n{expected}\nbut got:\n{actual}"
print("passed")6. A number-guessing game¶
random.randint(1, 100) gives a whole number from 1 to 100, inclusive, chosen at random. Run the
next cell a few times: the rolls of a die change each time.
for roll in range(5):
print(random.randint(1, 6), end=" ")
print()A computer’s random numbers come from a calculation that starts from a number called the seed. The same seed always gives the same numbers, which is what makes a program that uses randomness possible to test. Run the next cell several times: it sets the seed each time, so it prints the same rolls every time. Then change the seed and run it again.
random.seed(2026)
for roll in range(5):
print(random.randint(1, 6), end=" ")
print()Exercise L4.11 (LO-4.1, LO-4.3, ★★★, about 20 minutes)¶
Finish the guessing game in scratch/guess.py. The computer picks a secret number from 1 to
100. The game asks Guess: again and again, answers Too low or Too high after each wrong
guess, and ends when the player guesses right, printing how many guesses they took. A game with
a secret of 42 might go:
Guess: 50
Too high
Guess: 25
Too low
Guess: 42
Correct! Guesses: 3Keep the first three lines as they are. random.seed(7) makes the secret the same every time
you run it, so the game can be tested; the check also runs it with another seed. To play it for
real, delete the seed line and run the script in VS Code’s terminal.
Hint 1
The game doesn’t know how many guesses it will need, so it needs a while loop. A counter counts the guesses.
Hint 2
Either ask for the first guess before while guess != secret:, and again at the end of the block; or use while True:, and break when the guess is right.
%%writefile scratch/guess.py
import random
random.seed(7)
secret = random.randint(1, 100)run_script("scratch/guess.py", typed="50\n25\n42\n")source = open("scratch/guess.py", encoding="utf-8").read()
assert "random.seed(7)" in source, "Keep the line random.seed(7), so the game can be tested."
for seed in [7, 11, 2026]:
random.seed(seed)
secret = random.randint(1, 100)
low, high, guesses, typed, expected = 1, 100, 0, "", ""
while True:
guess = (low + high) // 2
guesses += 1
typed += f"{guess}\n"
expected += f"Guess: {guess}\n"
if guess < secret:
expected += "Too low\n"
low = guess + 1
elif guess > secret:
expected += "Too high\n"
high = guess - 1
else:
expected += f"Correct! Guesses: {guesses}\n"
break
with open("scratch/guess_seed.py", "w", encoding="utf-8") as file:
file.write(source.replace("random.seed(7)", f"random.seed({seed})"))
actual = output_of("scratch/guess_seed.py", typed=typed)
assert actual == expected, (
f"With seed {seed}, typing {typed.split()}, expected:\n{expected}\nbut got:\n{actual}"
)
print("passed")The check guessed by always choosing the middle of the numbers still possible, which never needs more than 7 guesses for 1 to 100. Can you see why?
Summary¶
In this lab you:
predicted the values and lengths of ranges;
stopped a loop that never ended, and fixed one that never started;
traced a loop in a table;
wrote an accumulator, a counter over a string, a search with
break, and an input-validation loop;counted the passes of nested loops, and printed a table with them; and
built a guessing game, and used a seed to make its randomness testable.
Next, the Module 4 practice gives you more exercises with answers, and Module 5 shows how to package code like this into functions you can name, reuse, and test.