Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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.

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).

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.

NameQuestion
n1How many times does a loop over range(7) run?
n2How many times does a loop over range(3, 10) run?
n3How many times does a loop over range(0, 20, 5) run?
n4How many times does a loop over range(20, 0, -5) run?
n5How many times does a loop over range(10, 3) run?
last1What is the last value of range(3, 10)?
last2What is the last value of range(0, 20, 5)?
last3What is the last value of range(20, 0, -5)?
Hint

The stop value is never included, even when counting down.

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?

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.)

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.

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 + 1
  • passes: how many passes the loop makes

  • last_n: the value of n after the loop

  • final_total and final_count: the values of total and count after the loop

Once the check passes, step through the loop in Python Tutor.

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?

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: 3
Hint

letter in "aeiouAEIOU" is True when letter is a vowel of either case.

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: 7

A 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.

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.

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.

Check your thinking with a counter. Change the loops in the next cell to each pair above, and run it.

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  16
Hint

print(f"{row * column:4}", end="") prints one product without ending the line. A print() after the inner loop ends the row.

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.

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.

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: 3

Keep 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.

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.