For loops and while loops
Use for to visit items and while when a changing condition controls repetition.
Learning objectives
- Trace a loop over
range. - Guard a while loop with a changing condition.
A bounded sequence
PYTHON
total = 0
for number in range(1, 5):
total += number
print(total)range(1, 5) yields 1, 2, 3, and 4: the start is included and the stop is excluded. The trace adds each value, so the final output is 10.
While and termination
A while reevaluates its condition before every iteration. Ensure the body changes a value used by that condition, or the loop can be infinite.
Common mistakes and references
- Do not modify a collection while iterating over it unless you understand the consequences.
- Use
breakfor an exceptional early exit, not to hide the normal termination rule.