Menu

Count Controlled Iteration (For Loops)

range()

The range() function produces a sequence of integers. Put it after in in a for loop and the loop variable takes each value from that sequence in turn, one value per repetition. Because range() fixes exactly how many values there are, the loop is count-controlled.

Three ways to write a range

range(stop) starts at 0, goes up in steps of 1 and stops before stop. So range(4) gives 0, 1, 2 and 3 โ€” four repetitions, not five.

range(start, stop) starts at start instead of 0, still going up in 1s and still stopping before stop.

range(start, stop, step) adds a third value, the step, which is the gap between neighbouring values. A positive step counts upwards, so range(2, 11, 3) jumps 2, 5, 8. A negative step counts downwards, which is how you make a loop run backwards; here start must be larger than stop.

In every form the stop value is never included, so the loop ends before reaching it. With a negative step, start must be larger than stop for the loop to run at all.

CallValues the loop variable takes
range(4)0, 1, 2, 3
range(2, 6)2, 3, 4, 5
range(1, 8, 3)1, 4, 7
range(9, 3, -2)9, 7, 5

Worked example

Here the loop uses a negative step so the checkpoints are scored from 4 down to 1. The loop variable checkpoint holds 4 on the first repetition and 1 on the last, and the line inside the loop runs four times because the range supplies four values.

# Score four checkpoints, counting down from 4 to 1
for checkpoint in range(4, 0, -1):
    points = checkpoint * 10
    print("Checkpoint " + str(checkpoint) + " scores " + str(points))

Output:

Checkpoint 4 scores 40
Checkpoint 3 scores 30
Checkpoint 2 scores 20
Checkpoint 1 scores 10

Practise this