6.2.2 – Count-controlled loops

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.

Python
for lap in range(4):
    print(lap)
print("Complete")
Output
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.

ExpressionValuesPasses
range(4)0, 1, 2, 34
range(1, 5)1, 2, 3, 44
range(2, 8, 2)2, 4, 63
range(5, 0, -2)5, 3, 13
range(1, 1)none0
range(3, 4)31

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.

Python
total = 0
for number in range(1, 5):
    total = total + number
    print(total)
print("Final:", total)
Passnumbertotal after update
111
223
336
4410

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:

Python
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