Condition Controlled Iteration (While Loops)
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.
The index has four separate jobs, and each one belongs in a particular place:
| Job | Where it goes |
|---|---|
| Initialise the index | Before the loop starts |
| Test the index | In the while condition |
| Use the index | Inside the body |
| Update the index | Inside the body |
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.
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.
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.
| position | Is the position less than the length? | Score at that position | Output |
|---|---|---|---|
| 0 | 0 is less than 4: True | 12 | 12 |
| 1 | 1 is less than 4: True | 8 | 8 |
| 2 | 2 is less than 4: True | 15 | 15 |
| 3 | 3 is less than 4: True | 4 | 4 |
| 4 | 4 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.
Edexcel GCSE Computer Science · Condition Controlled Iteration (While Loops)