Loading...
A loop repeats a controlled change of state. Identify its starting state, continuation condition and update, then test whether the intended work happens the correct number of times.
What you'll be able to do
Definite iteration is appropriate when the required traversal or count is known, such as visiting every item in a collection. Indefinite iteration continues until a condition changes, for example accepting valid input. A pre-condition loop may execute zero times; a post-condition loop executes its body at least once.
Python has for and while constructs but no dedicated repeat-until statement. A while True loop with a carefully placed break can express a post-condition pattern. In language-independent work, state whether the written condition means continue while true or stop when true.
A trace table records variables, tested conditions and output after relevant steps. Initialise an accumulator before adding values, update a counter at the intended point, and distinguish the final counter value from the number of body executions.
Python range(start,stop) excludes stop. Summing 1 through 4 uses range(1,5), not range(1,4). For nested loops, a complete inner traversal occurs for each outer iteration unless an explicit branch exits it. Count iterations from the control flow rather than multiplying arbitrary variable values.
A terminating loop must make progress towards a false continuation condition or a reached exit. If a control variable is never updated, a condition that starts true may stay true indefinitely. Updating the wrong variable can be harder to notice than omitting an update.
Test an empty collection, one element and the final permitted boundary. A useful invariant states what remains true after every completed iteration, such as total equalling the sum of the values already visited. It supports a correctness argument, while tests show behaviour for particular cases.
total = 0
for number in range(1, 5):
total = total + number
print(total)Scroll horizontally to see the full code or table.| After number | total |
|---|---|
| Start | 0 |
| 1 | 1 |
| 2 | 3 |
| 3 | 6 |
| 4 | 10 |
Attempt the task before opening its worked response. Record each change of state, explain the rule used, and check the result against the original requirements. Code examples labelled Python 3 use that language’s conventions; pseudocode states its own assumptions.
Common mistakes to avoid
Key takeaways
Test yourself
Answer a few questions, then review anything you missed.
Start with the quiz above to check the key ideas. You can also choose another topic from the practice library.