计算机科学 · 第 1 册 · 1–9 年级

Primary & Middle School Computer Science

本书暂未推出简体中文版。现有版本:English。

Primary & Middle School Computer Science · 1–9 年级

18Repeating with while

Tom wants a game that costs 50 coins. He saves 3 coins every week. How many weeks must he wait? He could work it out, but he could also just count: one week, 3 coins; two weeks, 6 coins; and so on, as long as he has fewer than 50 coins. A for loop needs to know in advance how many times to turn, and here that number is exactly what we are looking for.

You already know

A for loop repeats its block a known number of times (Chapter 16). A comparison such as coins < 50 gives True or False (Chapter 17). An algorithm can repeat steps until a condition becomes true (Chapter 10).

18.1 Repeating as long as a condition holds

Definition 18.1 (While loop)

A while loop repeats its block as long as a condition is true: while condition: followed by an indented block. The condition is checked before every turn; as soon as it is false, the loop stops and the program goes on after the block.

n = 5
while n > 0:
    print(n)
    n = n - 1
print("Lift-off!")
Listing 18.1. A countdown. code/grade-6/05-while-loops/listings/countdown.py
$ python countdown.py
5
4
3
2
1
Lift-off!
Output 18.1. When n reaches 0, the condition n > 0 is false and the loop stops.
A while loop is a cycle with the test at its door: the block runs, then the program goes back to the test. If the test is false the very first time, the block never runs at all.
A while loop is a cycle with the test at its door: the block runs, then the program goes back to the test. If the test is false the very first time, the block never runs at all.

18.2 Counters and running totals

Tom’s savings need two variables that change at each turn: the number of coins and the number of weeks.

Definition 18.2 (Counter and running total)

A counter is a variable that starts at 0 and goes up by 1 each time something happens. A running total is a variable that starts at 0 and adds each new value as it comes.

coins = 0
weeks = 0
while coins < 50:
    coins = coins + 3      # Tom saves 3 coins each week
    weeks = weeks + 1
print(f"{weeks} weeks: {coins} coins")
Listing 18.2. Tom’s savings. code/grade-6/05-while-loops/listings/savings.py
$ python savings.py
17 weeks: 51 coins
Output 18.2. After 16 weeks Tom has 48 coins, still fewer than 50; after 17 weeks he has 51.
The trace of  as a filling bar: one row per turn of the loop. The test coins < 50 is still true after week 16 (48 coins), and false after week 17 (51 coins).
The trace of Listing 18.2 as a filling bar: one row per turn of the loop. The test coins < 50 is still true after week 16 (48 coins), and false after week 17 (51 coins).

A running total can also add numbers typed by the user. Since we do not know how many numbers will come, we agree on a special value that means “stop”: here, 0. The program reads one number before the loop, and the next one at the end of each turn, so the condition always tests the latest number.

total = 0
number = int(input("Number (0 to stop): "))
while number != 0:
    total = total + number
    number = int(input("Number (0 to stop): "))
print("Total:", total)
Listing 18.3. Adding typed numbers until 0. code/grade-6/05-while-loops/listings/sum_until_zero.py
$ python sum_until_zero.py
Number (0 to stop): 12
Number (0 to stop): 7
Number (0 to stop): 30
Number (0 to stop): 0
Total: 49
Output 18.3. 12+7+30=4912 + 7 + 30 = 49; the 0 only stops the loop.

With a counter as well, the program can compute an average: the total divided by the number of values. A mark can be 0, so here the stop value is −1-1.

total = 0
count = 0
mark = float(input("Mark (-1 to stop): "))
while mark != -1:
    total = total + mark
    count = count + 1
    mark = float(input("Mark (-1 to stop): "))
print(f"{count} marks, average {total / count}")
Listing 18.4. The average of typed marks. code/grade-6/05-while-loops/listings/average.py
$ python average.py
Mark (-1 to stop): 14
Mark (-1 to stop): 9.5
Mark (-1 to stop): 17
Mark (-1 to stop): 12.5
Mark (-1 to stop): -1
4 marks, average 13.25
Output 18.4. (14+9.5+17+12.5)÷4=13.25(14 + 9.5 + 17 + 12.5) \div 4 = 13.25.

18.3 The loop that never ends

Definition 18.3 (Infinite loop)

An infinite loop is a loop whose condition never becomes false: the program keeps turning and never reaches the lines after the loop.

Tom first wrote his savings program with != instead of <: “as long as I do not have exactly 50 coins”. But 3 coins a week give 48, then 51: never exactly 50.

coins = 0
while coins != 50:
    coins = coins + 3
print("Saved 50 coins")
Listing 18.5. Waiting for exactly 50 coins. code/grade-6/05-while-loops/listings/forever.py
$ python forever.py

[killed after 2 s]
Output 18.5. The program prints nothing and never ends. In this book, a program that runs too long is stopped after 2 seconds.

On a computer, a program caught in an infinite loop is stopped by pressing Ctrl and C together in its terminal. To fix the loop, check two things: the block must change a variable of the condition, and the change must lead the condition to become false. Here, coins < 50 becomes false as soon as the 50 coins are reached or passed:

coins = 0
while coins < 50:
    coins = coins + 3
print("Saved", coins, "coins")
Listing 18.6. The condition becomes false. code/grade-6/05-while-loops/listings/fixed_forever.py
$ python fixed_forever.py
Saved 51 coins
Output 18.6. The loop stops.

18.4 Choosing between for and while

Any for loop over a range can be written with while and a counter, but it is longer, and forgetting the line that changes the counter gives an infinite loop.

for n in range(3, 0, -1):
    print("for:", n)

n = 3
while n > 0:
    print("while:", n)
    n = n - 1
Listing 18.7. The same countdown, both ways. The while version must start, test and change n itself. code/grade-6/05-while-loops/listings/for_and_while.py
$ python for_and_while.py
for: 3
for: 2
for: 1
while: 3
while: 2
while: 1
Output 18.7. The two loops print the same numbers.

Method 18.4 (Choosing a loop)

If the number of turns is known before the loop starts (“for each of the 5 squares”, “for every age from 0 to 80”), use for. If the loop must go on until something happens (“until 0 is typed”, “as long as the guess is wrong”), use while, and check that its condition will become false.

How many digits does a whole number have? We do not know in advance, but we can remove its last digit with // 10 until a single digit is left, and count:

n = int(input("A whole number: "))
digits = 1
while n >= 10:
    n = n // 10       # remove the last digit
    digits = digits + 1
print("Digits:", digits)
Listing 18.8. Counting digits. code/grade-6/05-while-loops/listings/digits.py
$ python digits.py
A whole number: 2026
Digits: 4
Output 18.8. 2026, 202, 20, 2: three turns, plus the last digit.

18.5 A number-guessing game

Two players: the first types a secret number from 1 to 100 while the second looks away, and the program prints a few empty lines; the second guesses, and the program answers “higher” or “lower” until the guess is right, counting the guesses.

secret = int(input("Player 1, the secret number (1 to 100): "))
print("\n" * 3)          # a few empty lines before player 2 plays
guesses = 1
guess = int(input("Player 2, your guess: "))
while guess != secret:
    if guess < secret:
        print("Higher!")
    else:
        print("Lower!")
    guesses = guesses + 1
    guess = int(input("Your guess: "))
print(f"Found in {guesses} guesses!")
Listing 18.9. A two-player guessing game. code/grade-6/05-while-loops/listings/guess.py
$ python guess.py
Player 1, the secret number (1 to 100): 37




Player 2, your guess: 50
Lower!
Your guess: 25
Higher!
Your guess: 37
Found in 3 guesses!
Output 18.9. The secret was 37.

A good player always guesses in the middle of the numbers still possible: each answer then removes half of them.

The numbers still possible (blue) before each guess (red line), in the game above. Halving the possible numbers, 7 guesses are always enough for 1 to 100.
The numbers still possible (blue) before each guess (red line), in the game above. Halving the possible numbers, 7 guesses are always enough for 1 to 100.

18.6 Exercises

Exercise 18.1 ★

What does this program print?

n = 5
while n > 0:
    print(n)
    n = n - 2
Listing 18.10. Counting down by two. code/grade-6/05-while-loops/exercises/by_two.py
Solution

Solution of Exercise 18.1.

5, 3 and 1. After 1, n becomes −1-1, and the condition n > 0 is false.

Exercise 18.2 ★

How many times does the block of this loop run? What is the last number printed?

n = 1
while n < 100:
    n = n * 3
    print(n)
Listing 18.11. Count the turns. code/grade-6/05-while-loops/exercises/turns.py
Solution

Solution of Exercise 18.2.

5 times: n becomes 3, 9, 27, 81 and 243. After 81 the test 81<10081 < 100 is still true, so the block runs once more; 243 is the last number printed.

Exercise 18.3 ★

What does this program print? Make its trace table.

total = 0
i = 1
while i <= 4:
    total = total + i * i
    i = i + 1
print(total)
Listing 18.12. A running total. code/grade-6/05-while-loops/exercises/squares_total.py
Solution

Solution of Exercise 18.3.

turntotali
before01
112
253
3144
4305

With i equal to 5 the test i <= 4 is false: the program prints 30, which is 1+4+9+161 + 4 + 9 + 16.

Exercise 18.4 ★

Write a program that adds the whole numbers from 1 to 100 with a while loop.

Solution

Solution of Exercise 18.4.

total = 0
i = 1
while i <= 100:
    total = total + i
    i = i + 1
print(total)
The sum of 1 to 100. code/grade-6/05-while-loops/exercises/sum100.py

It prints 5050.

Exercise 18.5 ★★

This program never stops. Why? Fix it so that it prints the numbers from 0 to 9.

i = 0
while i < 10:
    print(i)
Listing 18.13. A loop that never ends. code/grade-6/05-while-loops/exercises/never_bug.py
Solution

Solution of Exercise 18.5.

Nothing in the block changes i: it stays 0, and i < 10 stays true. Add i = i + 1 at the end of the block, indented like the print.

Exercise 18.6 ★★

This program should print 1+2+⋯+10=551 + 2 + \dots + 10 = 55, but prints 45. Which value is missing, and why? Fix it.

# The sum of 1, 2, ..., 10?
total = 0
i = 1
while i < 10:
    total = total + i
    i = i + 1
print(total)
Listing 18.14. A total that misses a value. code/grade-6/05-while-loops/exercises/total_bug.py
Solution

Solution of Exercise 18.6.

The 10 is missing: when i reaches 10, the test i < 10 is false, so 10 is never added. With while i <= 10: the program prints 55.

Exercise 18.7 ★★

Starting from 1 and doubling again and again, which is the first number above 1,000? Write a program that finds it and counts the doublings.

Solution

Solution of Exercise 18.7.

power = 1
doublings = 0
while power <= 1000:
    power = power * 2
    doublings = doublings + 1
print(power, "after", doublings, "doublings")
Doubling past 1,000. code/grade-6/05-while-loops/exercises/doubling.py

It prints 1024 after 10 doublings: 512 is still not above 1,000, and the next doubling gives 1,024.

Exercise 18.8 ★★

Write a program that asks for a whole number and prints the sum of its digits: 2026 gives 2+0+2+6=102 + 0 + 2 + 6 = 10. Use % 10 to get the last digit.

Solution

Solution of Exercise 18.8.

n = int(input("A whole number: "))
total = 0
while n > 0:
    total = total + n % 10     # the last digit
    n = n // 10                # remove it
print("Sum of the digits:", total)
The sum of the digits. code/grade-6/05-while-loops/exercises/digit_sum.py

Exercise 18.9 ★★

How many turns does while n > 1: n = n // 2 take when n starts at 100? Make the trace table.

Solution

Solution of Exercise 18.9.

n takes the values 50, 25, 12, 6, 3 and 1: 6 turns. 25//225 // 2 is 12 and 3//23 // 2 is 1, since // drops the remainder.

Exercise 18.10 ★★★

Write a program that asks “Have you finished your homework?” again and again, until the answer is yes.

Solution

Solution of Exercise 18.10.

The question is asked once before the loop and again at the end of each turn.

answer = input("Have you finished your homework? ")
while answer != "yes":
    print("Then go and finish it!")
    answer = input("Have you finished your homework? ")
print("Well done.")
Asking until the answer is yes. code/grade-6/05-while-loops/exercises/ask_yes.py

Exercise 18.11 ★★★

In Listing 18.2, replace the 3 coins a week by any whole number of coins greater than 0. Explain why the loop always stops. Would it still stop with 0 coins a week?

Solution

Solution of Exercise 18.11.

With cc coins a week, cc at least 1, coins grows by at least 1 at each turn: after 50 turns at most, it is at least 50, and the test coins < 50 is false. With 0 coins a week, coins stays 0 for ever: an infinite loop.

Exercise 18.12 ★★★

Change the guessing game so that player 2 has at most 7 guesses; after the seventh wrong guess, the program says that player 1 wins and shows the secret.

Solution

Solution of Exercise 18.12.

The condition gains a second part with and: the loop also stops after the seventh guess. After the loop, an if tells why it stopped.

secret = int(input("Player 1, the secret number (1 to 100): "))
print("\n" * 3)
guesses = 1
guess = int(input("Player 2, your guess: "))
while guess != secret and guesses < 7:
    if guess < secret:
        print("Higher!")
    else:
        print("Lower!")
    guesses = guesses + 1
    guess = int(input("Your guess: "))
if guess == secret:
    print(f"Found in {guesses} guesses!")
else:
    print("Seven guesses: player 1 wins. The number was", secret)
At most 7 guesses. code/grade-6/05-while-loops/exercises/guess_limit.py

History — An unsolved problem

The game of the weekend problem below is often called the Collatz problem, after the mathematician Lothar Collatz, who wrote down questions of this kind in his notebooks in the 1930s. It remains unsolved: nobody has proved that every start comes down to 1, and nobody has found a start that does not.

18.7 Problem: The 3n + 1 Game

Problem 18.1

Weekend problem — does every number come down to 1?

Start from a whole number. If it is even, halve it; if it is odd, triple it and add 1. Do the same with the result, again and again, and stop when you reach 1. Each change is one step. From 3, for instance: 3, 10, 5, 16, 8, 4, 2, 1, seven steps.

Part I — By hand.

  1. Play the game from 6. How many steps does it take? What is the highest number reached?
  2. Play it from 7. How many steps, and what is the highest number?
  3. Why does the game end at once when the number is a doubling of 1, such as 16, 32 or 64? How many steps does 64 take?

Part II — A program.

n = int(input("Start: "))
steps = 0
highest = n
while n != 1:
    if n % 2 == 0:
        n = n // 2
    else:
        n = 3 * n + 1
    steps = steps + 1
    if n > highest:
        highest = n
print("steps:", steps, "highest:", highest)
Listing 18.15. Steps and highest number for a typed start. code/grade-6/05-while-loops/listings/collatz.py
  1. Which variables of Listing 18.15 are counters, and which keeps a record? Why must highest start at the starting number?
  2. Run the program for 6 and 7. Does it agree with your answers?
  3. Run it for 27. What do you notice?
  4. Write a program that plays the game from every start from 1 to 99 and prints the start that takes the most steps, with its number of steps. (Put the while loop inside a for loop.)

Part III — An open question.

  1. For the start you found in question 7, what is the highest number reached?
  2. Your program of question 7 stopped for every start below 100. Does that prove that every start reaches 1?
  3. What would happen to your program if some start never reached 1?
  4. Mathematicians have played this game with computers for every start up to enormous numbers, and all reached 1. Yet nobody knows whether every start does. Explain the difference between “checked for many numbers” and “proved for all numbers”.
  5. State the result of question 7.
Solution

Solution of Problem 18.1.

1. 6, 3, 10, 5, 16, 8, 4, 2, 1: 8 steps; the highest number is 16.

2. 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1: 16 steps; the highest is 52.

3. A doubling of 1 is even, its half is again a doubling of 1, and so on down to 1: the game only halves. 64, 32, 16, 8, 4, 2, 1: 6 steps.

4. steps is a counter (one more at each turn). highest keeps the largest number seen so far; it starts at the starting number because the start itself may be the highest, as for 16.

5. It prints steps: 8 highest: 16 for 6 and steps: 16 highest: 52 for 7, as found by hand.

6. 27, a small start, takes 111 steps and climbs as high as 9,232 before coming down:

$ python collatz.py
Start: 27
steps: 111 highest: 9232
Output 18.10. The start 27.

7. The while loop of Listing 18.15 goes inside a for loop over the starts, with a record of the best start:

# Which start below 100 takes the most steps to reach 1?
best_start = 1
best_steps = 0
for start in range(1, 100):
    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("start:", best_start, "steps:", best_steps)
The start below 100 with the most steps. code/grade-6/05-while-loops/listings/collatz_record.py
$ python collatz_record.py
start: 97 steps: 118
Output 18.11. 97 takes 118 steps.

8. Running Listing 18.15 with 97: the highest number reached is 9,232, the same as for 27: the two paths meet at 94 and go on together.

9. No. It proves that the starts from 1 to 99 reach 1, and nothing about 100 or any larger start.

10. Its while loop would never end for that start: an infinite loop, and the program would print nothing.

11. “Checked” means that each number tried reached 1. “Proved” would mean an argument showing that every number, without exception, reaches 1. There are infinitely many whole numbers, so no computer can try them all; only a proof could settle the question, and nobody has found one.

12. Result. Among the starts below 100, 97 takes the most steps to reach 1: 118 steps.

本章定义的术语

在术语表中查看全部 1050 个术语