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.

These exercises practice what the Module 4 reading explained. They aren’t graded. Work each one on paper first, then check your answer, and only then run the code to confirm it. The answers are in the collapsed blocks; open one only after you have an answer of your own.

Worked example: tracing a while loop

How many digits does 4096 have? This loop counts them by removing the last digit with // 10 until nothing is left:

n = 4096
digits = 0
while n > 0:
    n = n // 10
    digits = digits + 1
print(digits)
Checkn before the passn > 0n afterdigits after
14096True4091
2409True402
340True43
44True04
50False

It prints 4. The loop ends because each pass makes n smaller, and // 10 of a single digit is 0. (For n = 0 it would print 0, though 0 has one digit: a case worth testing.)

Exercise 4.1 (LO-4.1, LO-4.3, ★, about 10 minutes)

Finish this trace. The first two rows are done. What does the program print?

n = 100
steps = 0
while n > 1:
    n = n // 2
    steps = steps + 1
print(steps, n)
Checkn beforen > 1n aftersteps after
1100True501
250True252
3
Answer
Checkn beforen > 1n aftersteps after
325True123
412True64
56True35
63True16
71False

It prints 6 1.

Exercise 4.2 (LO-4.1, ★★, about 10 minutes)

For each loop, say whether it ends, never ends, or never runs. For those that end, say how many passes they make.

  1. i = 0, then while i < 10: with i = i + 2 in the block

  2. i = 1, then while i != 10: with i = i + 2 in the block

  3. i = 10, then while i < 10: with i = i + 1 in the block

  4. i = 10, then while i > 0: with i = i - 3 in the block

Answer
  1. It ends after 5 passes: i goes 2, 4, 6, 8, 10, and 10 < 10 is false.

  2. It never ends: i is always odd (1, 3, 5, …), so it skips 10, and i != 10 stays true. A condition with < instead of != would end; checking for an exact value is fragile.

  3. It never runs: 10 < 10 is false at the start.

  4. It ends after 4 passes: i goes 7, 4, 1, -2.

Worked example: choosing a range

Which range gives the odd numbers from 1 to 19?

  1. Start at 1, and step by 2: range(1, ?, 2).

  2. The last value wanted is 19, and the stop is excluded, so the stop must be past 19: 20 or 21 both work, because the next value after 19 is 21.

range(1, 20, 2) gives 1, 3, …, 19.

Exercise 4.3 (LO-4.2, ★, about 10 minutes)

Write a range for each sequence.

  1. 1, 2, …, 10

  2. 2, 4, …, 20

  3. 10, 9, …, 1

  4. 7, 14, …, 49 (the multiples of 7 below 50)

Answer
  1. range(1, 11)

  2. range(2, 21, 2) (or a stop of 22)

  3. range(10, 0, -1): counting down, the stop 0 is excluded.

  4. range(7, 50, 7)

Exercise 4.4 (LO-4.2, LO-4.3, ★★, about 15 minutes)

Write a loop that builds the reverse of a string, using an accumulator that starts as the empty string. For text = "stressed", it should build "desserts".

Hint

Put each new letter in front of what you have built so far, not after it.

Answer
text = "stressed"
reversed_text = ""
for letter in text:
    reversed_text = letter + reversed_text
print(reversed_text)

After s, t, and r, reversed_text is "rts": each letter goes in front. Module 6 shows a shorter way, text[::-1].

Exercise 4.5 (LO-4.3, ★★, about 15 minutes)

Write a script, average.py, that reads test scores until the user types -1, then prints their average with one decimal. A value such as -1 that marks the end of the input is called a sentinel. If the first value is -1, print No scores instead of dividing by zero.

Score (-1 to finish): 80
Score (-1 to finish): 90
Score (-1 to finish): 70
Score (-1 to finish): -1
Average: 80.0
Hint

You need two accumulators, one for the total and one counting the scores. The sentinel must not be added to either.

Answer
total = 0
count = 0
score = int(input("Score (-1 to finish): "))
while score != -1:
    total = total + score
    count = count + 1
    score = int(input("Score (-1 to finish): "))
if count == 0:
    print("No scores")
else:
    print(f"Average: {total / count:.1f}")

Reading the next score at the end of the block, not the start, keeps the sentinel out of the total.

Exercise 4.6 (LO-4.3, ★★, about 15 minutes)

A whole number is prime if it is 2 or more and no number from 2 up to one less than itself divides it. Write a loop that sets is_prime to True or False for a number number. Stop searching as soon as you find a divisor. Test it with 1, 2, 9, 13, 91, and 97.

Answer
is_prime = number >= 2
for divisor in range(2, number):
    if number % divisor == 0:
        is_prime = False
        break

1, 9, and 91 aren’t prime (91 is 7 × 13); 2, 13, and 97 are. For 2, the range is empty, so the loop never runs, and is_prime keeps its starting value, True. Starting with number >= 2 handles 1, and also 0 and negative numbers.

Exercise 4.7 (LO-4.4, ★, about 10 minutes)

How many times does the innermost block run in each?

  1. for i in range(10):
        for j in range(i + 1, 10):
            ...
  2. for a in range(2):
        for b in range(3):
            for c in range(4):
                ...
Answer
  1. 45: for i from 0 to 9, the inner loop runs 9, 8, …, 1, 0 times, and 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 45. This loop visits each pair of different values once.

  2. 24: the ranges are independent, so 2 × 3 × 4.

Exercise 4.8 (LO-4.4, ★★, about 15 minutes)

Write nested loops that print this pattern for a height of 4, and work for any height:

1
1 2
1 2 3
1 2 3 4
Answer
height = 4
for row in range(1, height + 1):
    for column in range(1, row + 1):
        print(column, end=" ")
    print()

Each row ends with a space before the newline, which doesn’t show on screen.

Exercise 4.9 (LO-4.1, LO-4.3, LO-4.4, ★★★, about 25 minutes)

Start with a whole number. If it is even, halve it; if it is odd, multiply it by 3 and add 1. Repeat until you reach 1. From 6, this goes 6, 3, 10, 5, 16, 8, 4, 2, 1: 8 steps.

  1. Write a loop that counts the steps from a starting number n to 1.

  2. Wrap it in an outer loop that finds which start from 1 to 30 takes the most steps, and how many.

Hint

Part 1 is a while loop with a counter. For part 2, keep two more variables, the best start so far and its number of steps, and update them when a start beats them: the search pattern without break, because you must look at every start.

Answer
best_start = 1
best_steps = 0
for start in range(1, 31):
    n = start
    steps = 0
    while n != 1:
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + 1
        steps = steps + 1
    if steps > best_steps:
        best_start = start
        best_steps = steps
print(best_start, best_steps)

It prints 27 111: 27 climbs as high as 9,232 before it comes down. n = start matters: the inner loop changes n, and must not change the outer loop’s start. Every start anyone has tried reaches 1, but no one has proved that every start does, so this while loop is one whose ending no one can promise. The rule is known as the Collatz conjecture.