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

A for loop repeats once for every value in its range, so range is what decides how many times the loop runs and what the counter holds each time. It can be written with one, two or three numbers, and each one gives you more control.

One number: how many times

for counter in range(10):
    print(counter)

range(10) produces ten values, starting at 0: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

Counting from 0 looks odd the first time you see it. It is worth getting used to, because it means the number in the brackets is the number of repetitions, which is usually what you care about. range(10) repeats ten times, range(3) repeats three times.

Two numbers: from where to where

for counter in range(1, 5):
    print(counter)

The first number is where the counter starts, the second is where it stops, and the stop value is never reached. This prints 1, 2, 3, 4.

The stop value is the one that catches everybody out. range(1, 5) gives you four values, not five, because it stops before 5.

If you want the numbers 1 to 5, ask for range(1, 6). If a program has read a last number into a variable called end and has to include it, the range has to read range(start, end + 1).

Three numbers: how big a step

for counter in range(5, 25, 2):
    print(counter)

The third number is the step: how much the counter changes each time round. This one goes up in twos, so it prints 5, 7, 9 and so on up to 23. It never prints 25, for the same reason as before.

Leave the step out and it is 1, which is why the two-number version counts one at a time.

The numbers can be variables

Nothing says the values have to be typed in. They are ordinary numbers, so a variable works just as well.

num = 4
for counter in range(1, num):
    print(counter)

That prints 1, 2, 3. Change num to 7 and the same loop prints 1 to 6.

This is how a program lets the user decide how often something happens: read a number with input(), wrap it in int(), and hand it to range.

All together

Range Values the counter takes Repetitions
range(5) 0, 1, 2, 3, 4 5
range(1, 5) 1, 2, 3, 4 4
range(1, 6) 1, 2, 3, 4, 5 5
range(5, 25, 2) 5, 7, 9 ... 23 10
range(0) nothing at all 0

The last row is not a mistake. A range can be empty, and then the body of the loop never runs. A program that asks the user how many times to repeat something has to cope with the answer 0, and a for loop copes with it by doing nothing.

Help! My code doesn't work!

Make sure that you check for the following things:

  • The numbers inside range(...) are separated by commas.
  • With two numbers, the first is the start and the second is the stop.
  • The stop value is never reached, so add 1 to it if it has to be included.
  • A range built from user input is wrapped in int(), since range cannot work with text.
  • The counter is used, not the range: print(counter), never print(range).