Menu

Count Controlled Iteration (For Loops)

Python for Loops

A for loop repeats the same block of statements once for each value in a sequence. Programmers call it count-controlled iteration because the number of repetitions is fixed in advance by those values, rather than by a condition that gets tested each time round.

The parts of a for loop

Every for loop header in Python 3 is built from the same five parts, in this order:

  • for — the keyword that starts the loop.
  • a loop variable — a name you choose, which holds the current value.
  • in — the keyword that links the variable to the values.
  • an iterable — the object that supplies the values.
  • a colon — the mark that ends the header line.

The indented lines underneath the header are the loop body. They run once for each value the iterable supplies, and the loop stops by itself once the last value has been used. The loop variable can be used inside the body, where it holds a different value on each repetition.

The iterable is usually range(...), which produces a sequence of integers, or a data structure such as a string, a list or an array. Each one hands over its items one at a time, so the same header copes with three values or three hundred.

# Print a label for each of the six tables in a cafe
for tableNumber in range(1, 7):
    print("Table " + str(tableNumber) + " is ready")

Output:

Table 1 is ready
Table 2 is ready
Table 3 is ready
Table 4 is ready
Table 5 is ready
Table 6 is ready

Here the iterable supplies six numbers, so the print statement runs six times and every table gets its own label.

Why no condition is needed

The iterable decides everything. If it supplies six values, the body runs six times; if it supplies three, the body runs three times. There is no condition for you to test and no counter for you to add to: Python moves on to the next value automatically and stops when the values run out. That makes a for loop the natural choice when you know in advance how many repetitions you need, or when you want to visit every item in a data structure in turn.

Practise this