3.2.2 - Count-controlled iteration (Python)
When the required number of repetitions is known, a count-controlled loop avoids writing the same instructions repeatedly. You will choose Python range limits and trace how repeated updates build a result.
Choosing the repetition count
A count-controlled loop repeats a body a specified number of times.
Iteration
Executing a group of statements repeatedly. Definite, or count-controlled, iteration has a determined repetition count.
Python's for loop can take successive integers from range(). The stop value is excluded.
for ticket_number in range(1, 5):
print("Ticket", ticket_number)
print("Finished")
This displays tickets 1, 2, 3 and 4, then Finished once. The repeated statement is indented; the final statement is outside the loop. range(4) gives 0, 1, 2 and 3, also four values. range(2, 9, 2) gives 2, 4, 6 and 8 because its third value is the step. A negative step supports a countdown: range(3, 0, -1) gives 3, 2, 1.
AQA pseudocode FOR number ← 1 TO 4 includes both endpoints, so its Python equivalent uses range(1, 5). Do not copy the same upper number into both representations. AQA's loop counter is unavailable after the loop and never moves beyond its stated endpoint. Native Python normally retains the last assigned counter; this lesson's programs use it only inside the loop.
Choose definite repetition for printing four tickets or entering five measurements. If repetition depends on an unknown future event, a condition-controlled loop is more suitable.
Tracing counters and accumulators
A loop counter chooses the current iteration, while an accumulator keeps a result built across iterations.
total = 0
for number in range(1, 4):
total = total + number
print(total)
The initial zero gives the sum a starting value. For number 1, total becomes 1; for 2 it becomes 3; for 3 it becomes 6. The output outside the loop is therefore 6.
| Iteration | number | total after update |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
Trace one execution of the body for every value in the range. Resetting total inside the body would erase the earlier contributions, leaving only the final number. Moving print(total) inside the loop would display all the intermediate totals rather than just the final sum. Sequence inside the body and repetition of the body work together.
Building a running total
{"code":"total = 0\nfor number in range(1, 4):\n total = total + number\nprint(total)","instructions":"Predict the final total and run. Change the range stop from 4 to 5, run again and identify the additional iteration."}
Check the actual values generated by the range, the indentation of the body and whether an accumulator is initialised before repetition.