Drop hier links of afbeeldingen om ze aan de editor toe te voegen.

The loop in the previous topic kept going until the user typed the right answer, so nobody could say in advance how many times it would repeat. Very often you want the opposite: a loop that repeats a set number of times, whatever the user does.

The tool for that is a counter: an ordinary variable whose only job is to keep track of how many times the loop has gone round.

Three places a counter appears

A counter always shows up in exactly three places, and a loop needs all three to work.

  1. Before the loop, the counter is created and given a starting value.
  2. In the condition, the counter is compared against the value that should stop the loop.
  3. Inside the loop, the counter is changed, so that the condition eventually becomes false.

Miss any one of the three and the loop misbehaves. The easiest way to see that is to build one up a piece at a time.

Step 1: a counter that never changes

counter = 1

while counter < 5:
    print("Hello")

print("The loop has ended")

There is a counter, and there is a condition that compares it against 5. What there is not is anything inside the loop that changes counter. It holds 1 before the loop, it still holds 1 at the bottom of the body, and it will still hold 1 forever, so counter < 5 is true every single time.

This is an infinite loop. It prints Hello until you stop it, and it never reaches the last line.

Step 2: make the counter count

One extra line fixes it:

counter = 1

while counter < 5:
    print("Hello")
    counter = counter + 1

print("The loop has ended")
Hello
Hello
Hello
Hello
The loop has ended

counter = counter + 1 is the line you met in the Calculations topic. Python works out the right hand side first, using the value the variable holds at that moment, and only then stores the answer back in the same variable. So counter goes 1, 2, 3, 4, 5.

Follow it round. The condition is checked with counter holding 1, 2, 3 and 4, and each of those is less than 5, so the body runs four times. The fifth check happens with counter holding 5, 5 < 5 is false, and the loop ends.

Adding to a variable’s own value is so common that Python has a shorthand for it, which you also met in the Calculations topic. counter += 1 means exactly the same thing as counter = counter + 1, and counter -= 1 means the same as counter = counter - 1.

Use whichever of the two you find clearer. This chapter uses both.

Put the line that changes the counter as the last command inside the loop, and make sure it is indented. Move it out to the left margin and it is no longer part of the body, so it runs once after the loop instead of once per repetition, which puts you straight back to the infinite loop of step 1.

Step 3: use the counter

The counter is an ordinary variable, so you can look inside it while the loop is running:

counter = 1

while counter < 5:
    print("The counter is " + str(counter))
    counter += 1

print("The loop has ended")
The counter is 1
The counter is 2
The counter is 3
The counter is 4
The loop has ended

Printing the counter is the quickest way to see what a loop is really doing, and it shows something that catches people out: the last value the body ever sees is 4, not 5. The counter does reach 5, but by then the condition is false and the body is skipped.

counter holds a number, and "The counter is " is text. Python will not join those two with a +, and stops with a TypeError if you try. Wrap the number in str(), exactly as you did when you printed the answer to a calculation.

Choosing the numbers

Two decisions control how many times a counter loop repeats: what the counter starts at, and what the condition compares it against.

Start Condition Values the body sees Repetitions
counter = 1 counter < 5 1, 2, 3, 4 4
counter = 1 counter <= 5 1, 2, 3, 4, 5 5
counter = 0 counter < 5 0, 1, 2, 3, 4 5
counter = 10 counter > 0 10, 9, 8 ... 1 10

The last row counts down rather than up. Nothing says a counter has to grow: it just has to move towards the value that makes the condition false. A counter that starts at 10 and has counter -= 1 inside the loop works its way down to 0, which is where counter > 0 stops being true.

Make sure the counter moves in the direction that ends the loop. A counter that starts at 10, is tested with counter > 0 and then goes up by one each time never reaches 0, so the loop never ends.

Try it yourself

Run the code below and check that the output is the five lines you expect.

counter = 1

while counter < 5:
    print("The counter is " + str(counter))
    counter += 1

print("The loop has ended")

Then work out what each of these changes should do, make it, and run the code again to check:

Help! My code doesn't work!

Make sure that you check for the following things:

  • Iteration begins with while.
  • The while line has a condition.
  • The while line has a colon (:) at the end.
  • All the code you want to repeat is indented after the while, and all of it by the same amount. Never mix tabs and spaces in one file.
  • Any code that should run once the loop has finished is not indented.
  • The counter is given a starting value before the loop.
  • The line that changes the counter is inside the loop, and it moves the counter towards the value that makes the condition false.
  • A number is wrapped in str() before it is joined onto text with a +.