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)| Check | n before the pass | n > 0 | n after | digits after |
|---|---|---|---|---|
| 1 | 4096 | True | 409 | 1 |
| 2 | 409 | True | 40 | 2 |
| 3 | 40 | True | 4 | 3 |
| 4 | 4 | True | 0 | 4 |
| 5 | 0 | False |
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)| Check | n before | n > 1 | n after | steps after |
|---|---|---|---|---|
| 1 | 100 | True | 50 | 1 |
| 2 | 50 | True | 25 | 2 |
| 3 |
Answer
| Check | n before | n > 1 | n after | steps after |
|---|---|---|---|---|
| 3 | 25 | True | 12 | 3 |
| 4 | 12 | True | 6 | 4 |
| 5 | 6 | True | 3 | 5 |
| 6 | 3 | True | 1 | 6 |
| 7 | 1 | False |
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.
i = 0, thenwhile i < 10:withi = i + 2in the blocki = 1, thenwhile i != 10:withi = i + 2in the blocki = 10, thenwhile i < 10:withi = i + 1in the blocki = 10, thenwhile i > 0:withi = i - 3in the block
Answer
It ends after 5 passes:
igoes 2, 4, 6, 8, 10, and10 < 10is false.It never ends:
iis always odd (1, 3, 5, …), so it skips 10, andi != 10stays true. A condition with<instead of!=would end; checking for an exact value is fragile.It never runs:
10 < 10is false at the start.It ends after 4 passes:
igoes 7, 4, 1, -2.
Worked example: choosing a range¶
Which range gives the odd numbers from 1 to 19?
Start at 1, and step by 2:
range(1, ?, 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, 2, …, 10
2, 4, …, 20
10, 9, …, 1
7, 14, …, 49 (the multiples of 7 below 50)
Answer
range(1, 11)range(2, 21, 2)(or a stop of 22)range(10, 0, -1): counting down, the stop 0 is excluded.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.0Hint
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
break1, 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?
for i in range(10): for j in range(i + 1, 10): ...for a in range(2): for b in range(3): for c in range(4): ...
Answer
45: for
ifrom 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.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 4Answer
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.
Write a loop that counts the steps from a starting number
nto 1.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.