Menu

Count-Controlled Iteration

Count-controlled iteration

Iteration is the programming construct where a set of instructions is repeated. Along with sequence (steps carried out in order) and selection (choosing between different paths), it is one of the three basic constructs.

A count-controlled loop runs its body a set number of times. That number is already known before the loop begins. The number can be a fixed value written in the program, a variable holding a value worked out earlier, or input typed by the user. In Python, a for loop with range() is a count-controlled loop.

What repeats

The loop body is the code that repeats. It runs once for every value taken by the loop variable, so the loop variable changes on each pass. The repeated lines under the for line form the loop body.

This program prints the lap number for each of four laps:

for lap in range(1, 5):
    print("Lap " + str(lap))

Output:

Lap 1
Lap 2
Lap 3
Lap 4

The loop body runs four times, with lap holding 1, then 2, then 3, then 4. Each pass prints one line showing the current lap.

When to use it

Choose a count-controlled loop when you know before the loop starts how many passes are needed, such as printing 8 tickets or asking 5 questions. If you cannot tell how many passes will be needed before the loop starts, use a condition-controlled loop instead.

Practise this