Menu

Count Controlled Iteration (For Loops)

For Loop Totals and Tracking

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.

JobVariableSet before the loopUpdate inside the loop
Running totaltotaltotal = 0total = total + value
Counting itemscountcount = 0count = count + 1
Highest so farbestbest = 0if value > best: then best = value
Building a stringwordword = ""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.

A trace table of the six-shot basketball program: total and best after each pass, with best highlighted on the passes where it changes, ending with Total: 22 and Best shot: 7.

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.

Practise this