Skip to content

Repeating with while

~15 min ยท prerequisite: if, elif, and else

What you will be able to do

  • Write a while loop that repeats its block as long as a condition stays True.
  • Update a counter inside the loop so the condition eventually becomes False.
  • Recognize an infinite loop and stop it by changing the code that controls the condition.

The idea

A while loop starts with the word while, a condition, and a colon. Its block is indented, as in an if statement. Python checks the condition before each round. If the condition is True, Python runs the block once and then checks the condition again. When the condition is False, the loop ends, and Python continues with the first line after the block.

If the condition is False from the start, the block never runs. This is different from an if statement only in that the block can run many times.

The block must change something that the condition depends on. A variable that counts rounds is called a counter. A counter often starts at a value, goes up or down by one each round, and the loop stops when it reaches a limit.

Python has a short form for updating a variable. The augmented assignment count += 1 means the same as count = count + 1. The forms -=, *=, and //= work the same way, using subtraction, multiplication, and floor division.

If nothing in the block changes the condition, the condition stays True forever. This is an infinite loop. A program in an infinite loop keeps running until you stop it. In a terminal, you can press Ctrl+C to stop it, and Python then prints a traceback that ends with KeyboardInterrupt.

Worked example

count = 1
while count <= 3:
    print("Round", count)
    count += 1
print("Done")

Line by line, this is what Python does:

  1. count = 1 stores 1 in the counter.
  2. while count <= 3: checks the condition. 1 is at most 3, so the block runs.
  3. print("Round", count) shows Round 1.
  4. count += 1 changes count to 2. Then Python goes back to the condition.
  5. The same steps repeat for count equal to 2 and 3. When count becomes 4, the condition is False, and the loop ends.
  6. print("Done") runs after the loop.

The output is:

Round 1
Round 2
Round 3
Done

Try it

Each block checks its result with assert.

total = 0
n = 1
while n <= 5:
    total += n
    n += 1
assert total == 15
runs = 0
x = 10
while x < 5:
    runs += 1
    x += 1
assert runs == 0
value = 1
steps = 0
while value < 100:
    value = value * 2
    steps += 1
assert value == 128
assert steps == 7

countdown = 3
text = ""
while countdown > 0:
    text = text + str(countdown) + " "
    countdown -= 1
assert text == "3 2 1 "

The first block adds the numbers 1 to 5 by changing n each round. The second block never runs its body, because the condition is False at the start. The third block doubles value until it reaches 100 or more, and counts the doublings.

Common mistakes

  1. Forgetting to update the counter. The following loop never ends:

    i = 0
    while i < 3:  # never ends, do not run
        print(i)
    

    i stays 0, so i < 3 is always True. The output is an endless stream of 0. Press Ctrl+C to stop it. The loop never ends, so do not run this block in the browser runner.

  2. Stopping one round too early. The following check fails:

    count = 1
    rounds = 0
    while count < 3:
        rounds += 1
        count += 1
    assert rounds == 3
    
    AssertionError
    

    The loop runs for count equal to 1 and 2, so rounds is 2. Use count <= 3 if you want three rounds.

  3. Writing =+ instead of +=. The line count =+ 1 does not add 1. It means count = +1, which stores 1. The following check fails:

    count = 5
    count =+ 1
    assert count == 6
    
    AssertionError
    

    Write count += 1 to add 1 to the value.

  4. Expecting the loop to change a variable the condition does not use. In the following loop, total changes, but the condition checks count, so the loop never ends:

    count = 0
    total = 0
    while count < 3:  # never ends, do not run
        total += 1
    

    Update the variable that the condition checks, in this case count.

Practice

  1. Set n = 10. Use a while loop to subtract 3 from n each round while n is greater than 0. Assert that the final value of n is -2.
  2. Set x = 3. Use a while loop to double x until it is at least 50. Assert that x is 96.
  3. Use a while loop to count how many times you can halve 1000 with // before it reaches 0. Store the count in steps and assert that steps is 10.
  4. Set number = 1 and total = 0. Use a while loop to add the odd numbers 1, 3, 5, 7, and 9 to total. Assert that total is 25.
  5. Stretch: start with power = 1 and doublings = 0. Use a while loop to double power while it is at most 1000, and count the doublings. Assert that power is 1024 and doublings is 10.
Solution
  1. python n = 10 while n > 0: n -= 3 assert n == -2

  2. python x = 3 while x < 50: x = x * 2 assert x == 96

  3. python n = 1000 steps = 0 while n > 0: n = n // 2 steps += 1 assert steps == 10

  4. python number = 1 total = 0 while number <= 9: total += number number += 2 assert total == 25

  5. python power = 1 doublings = 0 while power <= 1000: power = power * 2 doublings += 1 assert power == 1024 assert doublings == 10

Recap

  • A while loop checks its condition before each round and runs the block while the condition is True.
  • The block must change a variable that the condition depends on. Otherwise the loop never ends.
  • += adds to a variable in place. A counter is a variable that changes each round.

Sources