Menu

Count-Controlled Iteration

Calculations with the loop variable

The loop variable is the variable named in a for line, such as day in for day in range(1, 5):. It holds a different value on each pass — 1, then 2, then 3, then 4 — so anything you do with it inside the loop can change each time. That is what makes count-controlled loops useful for repeating work a set number of times, instead of writing the same instruction out again and again.

Calculations and output that use the loop variable

Because the loop variable changes, you can drop it into a calculation or a message. Printing "Lap " + str(lap) inside a training loop labels every lap for you, and printing str(canteens * 6) tells you how many pupils can be seated once that many six-seat canteen tables are full. The calculation is written once, but the answer is different on every pass.

Here the loop variable form numbers each prompt, and each amount is added to a running total:

total = 0
for form in range(1, 4):
    raised = int(input("Amount raised by form " + str(form) + ": "))
    total = total + raised
print("Total raised: " + str(total))
print("Average per form: " + str(total / 3))

Output when the user types 25, 40, 55:

Amount raised by form 1: 25
Amount raised by form 2: 40
Amount raised by form 3: 55
Total raised: 120
Average per form: 40.0

Running totals and averages

A running total is built up one value at a time. Set it to zero before the loop, then add each new value inside the loop with a line such as total = total + raised. Three form groups raising 25, 40 and 55 give:

Pass (form)raised enteredtotal after the line
12525
24065
355120

An average can only be found once every value has been added, so the division belongs after the loop: 120 divided by 3 gives 40.0. Dividing inside the loop would only average the amounts collected so far, which is not the average of all three.

Putting total = 0 inside the loop instead of before it causes a logic error, because the total is wiped clean on every pass. It would end up holding only the last amount entered — 55 — so the total and the average would both be wrong.

Practise this