6.2.2 – Count-controlled loops
Use for and range to repeat a block a planned number of times. Trace start, stop and step, accumulate results, and reason through nested loops and zero-pass cases.
Count-controlled repetition
Count-controlled repetition runs a block for a known number of generated values. In Python, a for loop with range supplies those values one at a time. The loop body is indented and executes once for each value.
for lap in range(4):
print(lap)
print("Complete")
0
1
2
3
Complete
The loop variable lap receives 0, 1, 2 and 3 in turn. The stop value 4 is excluded. After the final pass, no values remain and control reaches the unindented print. That outer statement executes once, not once per pass.
A structured loop is entered through its header. Each pass returns to the header for the next value; its normal exit is reached when that sequence is exhausted. Repetition does not mean arbitrary jumps into the middle of a block.
Start, stop and step
The general form is range(start, stop, step). Start is included; stop is excluded. If start is omitted it defaults to 0; if step is omitted it defaults to 1. Step is the change between successive values and cannot be zero.
| Expression | Values | Passes |
|---|---|---|
range(4) | 0, 1, 2, 3 | 4 |
range(1, 5) | 1, 2, 3, 4 | 4 |
range(2, 8, 2) | 2, 4, 6 | 3 |
range(5, 0, -2) | 5, 3, 1 | 3 |
range(1, 1) | none | 0 |
range(3, 4) | 3 | 1 |
For a positive step, values continue while they are below stop. For a negative step, they continue while above stop. A positive step cannot take 5 towards a smaller stop of 0, so range(5, 0) is empty; it does not automatically reverse direction.
To print 2, 4 and 6, a stop of 8 works. Stops 7 or 8 generate the same sequence because the next possible value would be 8. The meaningful check is which values are generated, not whether a solution uses the model's exact stop literal.
Accumulate a total and count matches
An accumulator stores a running result. Initialise it before the loop, then update it inside. Reinitialising it on every pass would erase earlier work.
total = 0
for number in range(1, 5):
total = total + number
print(total)
print("Final:", total)
| Pass | number | total after update |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
| 4 | 4 | 10 |
The inner print shows a running total; the outer one reports the completed total. A counter instead increases by a fixed amount, often 1 per matching item. This loop asks for three scores and counts scores of at least 50:
passes = 0
for attempt in range(3):
score = int(input("Score: "))
if score >= 50:
passes = passes + 1
print("Passes:", passes)
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account