Menu

Writing and Refining Algorithms

For Loops

A for loop with range() is count-controlled: it repeats a block of code a set number of times, decided before the loop starts. The loop variable takes a new value on each pass, and the indented lines underneath run each time.

range(start, end) includes its start value but stops before its end value. So range(1, 5) runs four times: the loop variable is 1, then 2, then 3, then 4. The number of iterations is the difference between the end and start values, 5 - 1 = 4. If you write one value, such as range(5), Python starts at 0 and stops before 5, so it runs five times with values 0, 1, 2, 3 and 4.

For example, the program below prints a shelf number for a library display. It repeats once for each shelf from 1 up to, but not including, 5.

for shelf in range(1, 5):
    print("Shelf", shelf)

Output:

Shelf 1
Shelf 2
Shelf 3
Shelf 4

To count iterations, subtract: range(2, 9) runs 7 times (2, 3, 4, 5, 6, 7, 8), and range(4) runs 4 times (0, 1, 2, 3). The end value is not produced, so planning a loop means choosing the end value one higher than the last value you want.

Practise this

OCR GCSE Computer Science · Writing and Refining Algorithms