Menu

Count Controlled Iteration (For Loops)

Direct Iteration

Direct iteration is when a for loop steps through a data structure — a string, a list or an array — one item at a time, without you writing how many items there are. You name a loop variable and the data structure, then end the line with a colon. Python sets the loop variable to each item in turn, starting with the first and finishing with the last, so the indented body runs once for every item.

Because the loop visits every item, it suits jobs where each item must be processed and you never need an item's position. If you do need the position, use index-based iteration instead, where the loop variable holds an index rather than an item.

Why it copes with change

Nothing in the loop says how many items to visit, so the same loop works on a three-character code and a twelve-character one. Adding or removing an item changes the number of repetitions automatically. This is still count-controlled repetition: the count comes from the size of the data structure rather than from a number you typed in.

The program below counts the digits in a locker code, whatever its length.

lockerCode = input("Enter your locker code: ")
digitCount = 0

for character in lockerCode:
    if character.isdigit():
        digitCount = digitCount + 1

print("Digits found: " + str(digitCount))

Output when the user types P4T9:

Enter your locker code: P4T9
Digits found: 2

Typed in as P4T9, the loop variable and the count change like this:

Repetitioncharactercharacter.isdigit()digitCount
1PFalse0
24True1
3TFalse1
49True2

Flowchart of the for loop over lockerCode: take the next character, test isdigit, add 1 to digitCount when true, loop until no characters are left, then output digitCount. Notes show P4T9 giving 2.

The loop ends by itself once the last item has been used, so there is no condition for you to check and no way to run past the end of the data.

Practise this