---
title: "Repeating with while"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 18
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/18-repeating-with-while
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 18 — Repeating 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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) repeats its block a known number of times ([Chapter 16](https://one-course.com/books/computer-science/1/en/chapter/16-repeating-with-for-turtle-drawings#ch-g6-for-loops-turtle)). A [comparison](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) such as `coins < 50` gives `True` or `False` ([Chapter 17](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#ch-g6-if-else)). An [algorithm](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-algorithm) can repeat steps until a [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) becomes true ([Chapter 10](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#ch-g4-algorithms-repeat-and-decide)).

## 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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) is true: `while condition:` followed by an indented block. The [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) is checked before every turn; as soon as it is false, the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) stops and the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) goes on after the block.

```python
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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) `n > 0` is false and the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-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.](https://one-course.com/images/onecourse/chapters/computer-science-1/g6-while-loops/fig-5f4ab134a562.svg)

*A `while` [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) is a cycle with the test at its door: the block runs, then the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-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](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) 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](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) that starts at 0 and goes up by 1 each time something happens. A *running total* is a [variable](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) that starts at 0 and adds each new [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) as it comes.

```python
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).](https://one-course.com/images/onecourse/chapters/computer-science-1/g6-while-loops/fig-d18f98eaa8b3.svg)

*The trace of [Listing 18.2](#lst-g6-while-loops-savings) as a filling bar: one row per turn of the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop). The test `coins < 50` is still true after week 16 (48 coins), and false after week 17 (51 coins).*

A [running total](#def-g6-while-loops-counter) can also add numbers typed by the user. Since we do not know how many numbers will come, we agree on a special [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) that means “stop”: here, 0. The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) reads one number before the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop), and the next one at the end of each turn, so the [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) always tests the latest number.

```python
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
= 49$; the 0 only stops the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop).*

With a [counter](#def-g6-while-loops-counter) as well, the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) can compute an average: the total divided by the number of [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value). A mark can be 0, so here the stop [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) is $-1$.

```python
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) \div 4 = 13.25$.*

## 18.3 The loop that never ends

**Definition 18.3 (Infinite loop).**

An *infinite loop* is a [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) whose [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) never becomes false: the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) keeps turning and never reaches the lines after the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop).

Tom first wrote his savings [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-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.

```python
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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) prints nothing and never ends. In this book, a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that runs too long is stopped after 2 seconds.*

On a [computer](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-computer), a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) caught in an [infinite loop](#def-g6-while-loops-infinite) is stopped by pressing Ctrl and C together in its terminal. To fix the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop), check two things: the block must change a [variable](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of the [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition), and the change must lead the [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) to become false. Here, `coins < 50` becomes false as soon as the 50 coins are reached or passed:

```python
coins = 0
while coins < 50:
    coins = coins + 3
print("Saved", coins, "coins")
```

***Listing 18.6.** The [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) stops.*

## 18.4 Choosing between `for` and `while`

Any `for` [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) over a `range` can be written with `while` and a [counter](#def-g6-while-loops-counter), but it is longer, and forgetting the line that changes the [counter](#def-g6-while-loops-counter) gives an [infinite loop](#def-g6-while-loops-infinite).

```python
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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) print the same numbers.*

**Method 18.4 (Choosing a loop).**

If the number of turns is known before the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) starts (“for each of the 5 squares”, “for every age from 0 to 80”), use `for`. If the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-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:

```python
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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) prints a few empty lines; the second guesses, and the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) answers “higher” or “lower” until the guess is right, counting the guesses.

```python
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.](https://one-course.com/images/onecourse/chapters/computer-science-1/g6-while-loops/fig-0b65e4222552.svg)

*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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) print?

```python
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 of Exercise 18.1.**

5, 3 and 1. After 1, `n` becomes $-1$, and the [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) `n > 0` is false.

**Exercise 18.2 ★.**

How many times does the block of this [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) run? What is the last number printed?

```python
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 of Exercise 18.2.**

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

**Exercise 18.3 ★.**

What does this [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) print? Make its [trace table](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-trace-table).

```python
total = 0
i = 1
while i <= 4:
    total = total + i * i
    i = i + 1
print(total)
```

***Listing 18.12.** A [running total](#def-g6-while-loops-counter). code/grade-6/05-while-loops/exercises/squares_total.py*

**Solution of Exercise 18.3.**

| turn | `total` | `i` |
| --- | --- | --- |
| before | 0 | 1 |
| 1 | 1 | 2 |
| 2 | 5 | 3 |
| 3 | 14 | 4 |
| 4 | 30 | 5 |

With `i` equal to 5 the test `i <= 4` is false: the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) prints 30, which is $1 + 4 + 9 + 16$.

**Exercise 18.4 ★.**

Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that adds the whole numbers from 1 to 100 with a `while` [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop).

**Solution of Exercise 18.4.**

```python
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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) never stops. Why? Fix it so that it prints the numbers from 0 to 9.

```python
i = 0
while i < 10:
    print(i)
```

***Listing 18.13.** A [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) that never ends. code/grade-6/05-while-loops/exercises/never_bug.py*

**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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) should print $1 + 2 + \dots + 10 = 55$, but prints 45. Which [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) is missing, and why? Fix it.

```python
# 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](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value). code/grade-6/05-while-loops/exercises/total_bug.py*

**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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that finds it and counts the doublings.

**Solution of Exercise 18.7.**

```python
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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that asks for a whole number and prints the sum of its digits: 2026 gives $2 + 0 + 2 + 6 = 10$. Use `% 10` to get the last digit.

**Solution of Exercise 18.8.**

```python
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](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-trace-table).

**Solution of Exercise 18.9.**

`n` takes the [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) 50, 25, 12, 6, 3 and 1: 6 turns. $25 // 2$ is 12 and $3 // 2$ is 1, since `//` drops the remainder.

**Exercise 18.10 ★★★.**

Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that asks “Have you finished your homework?” again and again, until the answer is `yes`.

**Solution of Exercise 18.10.**

The question is asked once before the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) and again at the end of each turn.

```python
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](#lst-g6-while-loops-savings), replace the 3 coins a week by any whole number of coins greater than 0. Explain why the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) always stops. Would it still stop with 0 coins a week?

**Solution of Exercise 18.11.**

With $c$ coins a week, $c$ 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](#def-g6-while-loops-infinite).

**Exercise 18.12 ★★★.**

Change the guessing game so that player 2 has at most 7 guesses; after the seventh wrong guess, the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) says that player 1 wins and shows the secret.

**Solution of Exercise 18.12.**

The [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) gains a second part with `and`: the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) also stops after the seventh guess. After the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop), an `if` tells why it stopped.

```python
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.**

```python
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*

4. Which [variables](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of [Listing 18.15](#lst-g6-while-loops-collatz) are [counters](#def-g6-while-loops-counter) , and which keeps a record? Why must `highest` start at the starting number?
5. Run the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) for 6 and 7. Does it agree with your answers?
6. Run it for 27. What do you notice?
7. Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) inside a `for` [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) .)

**Part III — An open question.**

8. For the start you found in question 7, what is the highest number reached?
9. Your [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) of question 7 stopped for every start below 100. Does that prove that every start reaches 1?
10. What would happen to your [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) if some start never reached 1?
11. Mathematicians have played this game with [computers](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-computer) 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”.
12. State the result of question 7.

**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](#def-g6-while-loops-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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) of [Listing 18.15](#lst-g6-while-loops-collatz) goes inside a `for` [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) over the starts, with a record of the best start:

```python
# 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](#lst-g6-while-loops-collatz) 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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) would never end for that start: an [infinite loop](#def-g6-while-loops-infinite), and the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-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](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-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.
