Unit content
Loops and iteration
A loop repeats part of a program. Repetition can continue while a condition holds or can visit each value in a collection.
Condition-controlled loops
A while-style loop repeats as long as its condition remains true:
while balance > 0:
process_payment()
Something inside the loop must eventually make the condition false if the algorithm is intended to terminate.
Iterating over values
A for-style loop often processes each element of a collection:
sum = 0
for value in values:
sum = sum + value
After the loop, sum contains the accumulated total.
Loop state
A loop typically maintains state that changes from one iteration to the next: a counter, an accumulated result, a current position or a partially processed structure.
A useful way to reason about a loop is to identify what remains true before and after every iteration. Such a property is called a loop invariant.
Termination
An infinite loop may be intentional, as in a long-running server, or it may be a bug. For algorithms expected to finish, there must be progress toward a terminating condition.
Loops turn finite program text into computations whose number of steps depends on the input.