Repeating with while

Introduction

A while loop repeats its block as long as a condition stays True. Use it when you do not know in advance how many times to repeat, such as until the user gets an answer right.

A for loop is right when you can count the rounds. Many problems are not like that: keep asking until the password is right, keep dividing until nothing is left. These need a loop that decides for itself when to stop.

How it works

Counting down

n = 3
while n > 0:
    print(n)
    n -= 1
print("Go!")
Open in compiler

Each time Python reaches line 2 it checks n > 0. The calculation box shows the check every round: 3 > 0, 2 > 0, 1 > 0, and finally 0 > 0 → False, which ends the loop and moves on to line 5.

Something inside the loop must change the condition. Here n -= 1 (short for n = n - 1) brings n closer to 0 every round.

Stopping early with break

secret = 7
while True:
    guess = int(input("Guess: "))
    if guess == secret:
        print("Correct!")
        break
    print("Try again")

Input used: 3 ⏎ 9 ⏎ 7

Open in compiler

while True: would run forever on its own; break jumps out of the loop immediately. This example was recorded with three guesses, 3, 9 and 7, so the loop runs three times.

continue is the opposite kind of jump: it skips the rest of the block and goes straight back to the condition.

Syntax

while n > 0:
    n -= 1

while True:
    if done:
        break

Example

n = int(input())
total = 0
while n > 0:
    total += n % 10
    n = n // 10
print(total)

Input used: 4728

Open in compiler

This adds up the digits of 4728. Each round, n % 10 is the last digit and n // 10 removes it: 4728 → 472 → 47 → 4 → 0. Watch total grow in the variables panel: 8, 10, 17, 21.

Line by line

  1. n = int(input()) reads the number, which is 4728 in this recording.
  2. total = 0 starts the sum.
  3. while n > 0: is checked before each pass.
  4. total += n % 10 adds the last digit.
  5. n = n // 10 removes the last digit, which moves the loop towards its end.
  6. When n reaches 0, the loop stops and the total is printed.

Expected result

With this input:

4728

it prints:

21

In the real world

Programs that wait for something use this kind of loop. A game repeats until the player quits, a server repeats until it is shut down, and a download retries until it succeeds or gives up.

Common mistakes

  • Forgetting to change the variable in the condition. The loop never ends; the visualizer stops it after 1000 steps and says so.
  • Using while where for is simpler. If you know the number of rounds, for i in range(n): is clearer.
  • Off by one: while n >= 0 runs one more round than while n > 0.

Best practices

  • Before running a while loop, ask what makes it stop.
  • Prefer for when you know the number of rounds.
  • Keep the condition simple, and use break for unusual exits.

Summary

A while loop repeats as long as its condition holds, so its body must change something that the condition depends on. break leaves the loop and continue skips to the next pass. % 10 and // 10 take a number apart.

Practice

Read a number and print how many digits it has, using a while loop and // 10. Check that it prints 1 for the input 0.

Quick check

1. How many times does the body of n = 5 / while n > 2: n -= 1 run?
2. What does break do?
3. What is 4728 % 10?

Key takeaways

  • Use while when you cannot know the number of passes in advance.
  • Something in the body must move the loop towards its end.
  • break leaves only the loop it is in.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.