Count Controlled Iteration (For Loops)
A for loop can do more than repeat a line: it can build up a total, find a maximum or minimum, count items, or join a string together. Each one works the same way — a variable initialised outside the loop is updated once per repetition.
The variable you update is an accumulator (for totals, counts and strings) or a tracking variable (for maximums and minimums). It must be initialised before the loop, because the first pass adds to whatever the variable already holds. A total starts at 0, and so can a maximum when no value can be negative. Miss the initialisation and Python raises an error, as you cannot add to something that does not exist yet.
| Job | Variable | Set before the loop | Update inside the loop |
|---|---|---|---|
| Running total | total | total = 0 | total = total + value |
| Counting items | count | count = 0 | count = count + 1 |
| Highest so far | best | best = 0 | if value > best: then best = value |
| Building a string | word | word = "" | word = word + letter |
Here a player takes six shots at a basketball hoop. total collects the points and best tracks the highest single shot:
total = 0
best = 0
for attempt in range(6):
points = int(input("Points scored: "))
total = total + points
if points > best:
best = points
print("Total: " + str(total))
print("Best shot: " + str(best))Output when the user types 3, 5, 2, 7, 4, 1:
Points scored: 3
Points scored: 5
Points scored: 2
Points scored: 7
Points scored: 4
Points scored: 1
Total: 22
Best shot: 7
Only the indented lines repeat. The two print lines sit at the original indentation, so they run once, after the sixth shot has been added — put them inside the loop and you would see a running commentary instead of one final result.
Sometimes a variable must start fresh for each record. If an outer loop handles one player at a time, total = 0 goes inside the outer loop, just before that player's shots are processed. Otherwise the second player's total begins with the first player's points, and every figure after the first is wrong.
Finally, do not reuse the loop variable for another job inside the body. In for attempt in range(6), attempt already holds the current repetition number. Changing it will not alter how many times the loop repeats, but it wipes out the count you may need, so give your accumulator its own name.
Edexcel GCSE Computer Science · Count Controlled Iteration (For Loops)
Edexcel GCSE Computer Science · Two-dimensional Arrays (2D Lists)