Menu

Condition Controlled Iteration (While Loops)

While Loops and Data Structures

A while loop can visit every item in a data structure by using an index – a variable holding the position of the item you are looking at. The loop repeats while the index still points at a real item, so each item is reached once, in order.

Four jobs, four places

The index has four separate jobs, and each one belongs in a particular place:

JobWhere it goes
Initialise the indexBefore the loop starts
Test the indexIn the while condition
Use the indexInside the body
Update the indexInside the body

The four jobs of the index (initialise, test, use, update) with the list 12, 8, 15, 4 and the position moving 0 to 4, where 4 < 4 is False and the loop stops.

Moving a job changes the loop. If you initialise the index inside the body, it resets on every iteration. If you test the index but never update it, the condition never becomes false once it is true, so the loop never finishes.

Base the bound on the length

Testing the index against the length, using len(), means the same loop works whether the data structure holds 4 items or 400. A fixed bound suits only one size and fails when the data changes.

Use less than, not less than or equal to. Positions begin at 0, so the last item of a seven-item structure sits at position 6. An index equal to the length is past the end, so asking for the item at that position is invalid.

Worked example

Suppose a list holds four scores: 12, 8, 15 and 4. The loop prints each score; the trace table shows the index moving through the list.

positionIs the position less than the length?Score at that positionOutput
00 is less than 4: True1212
11 is less than 4: True88
22 is less than 4: True1515
33 is less than 4: True44
44 is less than 4: False––

The index starts at 0 before the loop, the condition tests it against the length, the body picks out one score per iteration, and the last line moves it on. After four iterations the index reaches 4, the condition is false and the loop stops.

Practise this