Count-Controlled Iteration
A for loop can take its values straight from a sequence — an ordered collection of items, such as the characters in a string — instead of counting through a range. Each pass gives the loop variable the next item in turn, so you never mention a position at all. The loop still repeats a set number of times: once for every item, so it is count-controlled iteration.
In the program below the loop runs once for every character in the combination, and digit holds a different character on each pass. The number of passes is decided automatically by how many characters the combination has, so you cannot get the count wrong.
combination = "8362"
for digit in combination:
print("Turn to " + digit)Output:
Turn to 8
Turn to 3
Turn to 6
Turn to 2
Iterating over the items is shorter and easier to read, so use it whenever each item is all you need: printing it, using it in a calculation, or testing it with an if. What you give up is any knowledge of where the item came from, because the loop never hands you its index.
When the position matters, write range(0, len(sequence)) instead. The loop variable then holds an index, counting 0 up to one less than the length, and you use that index to reach into the sequence. To compare the characters in matching places in two words, both words must be read with the same index at the same moment, and counting with range keeps them in step in a way the item-only loop cannot.
| What you write | Loop variable holds | Use it when |
|---|---|---|
for item in sequence: | each item in turn | you only need the item itself |
for i in range(0, len(sequence)): | each position, 0 to length - 1 | you need the position, or must match positions across sequences |
OCR GCSE Computer Science · Count-Controlled Iteration
OCR GCSE Computer Science · 1D Arrays