Menu

Pseudocode

FOR Loops

Repetition, also called iteration, means repeating statements. A FOR loop is count-controlled: it repeats a set number of times. WHILE and REPEAT UNTIL loops are condition-controlled.

When to use a FOR loop

Use a FOR loop when you know in advance how many repetitions are needed, or when you need to process a fixed range of values. A counter variable takes each value in the range in turn, and the statements in the loop body run once for each value. The loop header names the counter and the range it should take, then the repeated statements are written underneath. For example, if you want to print four lap numbers, the counter could take the values 1, 2, 3 and 4.

# Count-controlled FOR loop
for lap in range(1, 5):
    print("Lap " + str(lap))

Output:

Lap 1
Lap 2
Lap 3
Lap 4

Iterating over a data structure

A FOR loop can also iterate over every item in a data structure. Instead of a counter and a range, the loop visits each element of an array or each character in a string, one at a time. The loop variable holds the current item, so the same statements can process every item without you writing them out again.

# Iterating over each character in a string
for letter in "CODE":
    print(letter)

Output:

C
O
D
E

Practise this