Doing It Again
A loop repeats a block of code. The two staple forms are the while loop and the for loop.
A while loop repeats as long as a condition stays true, checking the condition before each pass:
i = 0
while i < 5:
print(i)
i = i + 1
This prints 0 1 2 3 4. Three ingredients keep it correct: an initialization (i = 0), a condition (i < 5), and an update (i = i + 1) that moves toward making the condition false. Forget the update and the condition never becomes false — an infinite loop that runs forever.
A for loop is designed for a known number of repetitions or for stepping through a collection: for i in range(5) runs the body for i = 0, 1, 2, 3, 4. Note that range(5) gives five values starting at 0 and stopping before 5 — a convention that is the source of the classic off-by-one error, where a loop runs one time too many or too few because a boundary (< vs <=) is wrong.
Two control statements adjust a loop from inside: break exits the loop immediately, and continue skips to the next iteration. Loops can also nest, one inside another — a nested loop running times inside a loop running times executes its inner body times, which matters for performance.
Common pitfall: the off-by-one error. A loopfor i in range(5)runs fori = 0..4(five times, stopping before 5), andwhile i <= 5runs one more time thanwhile i < 5. Always check whether the boundary should be included, and whether counting starts at 0 or 1.
A counter stepping along a number line from 0, ticking 0,1,2,3,4 under a "< 5" gate that turns the flow off exactly at 5 — the loop bound and the five iterations shown as discrete accent steps.