In addition to selecting which statements to execute, control statements are used to express repetition. If each line of code we wrote were only executed once, programming would be a very unproductive exercise. Only through repeated execution of statements do we unlock the full potential of computers. We have already seen one form of repetition: a function can be applied many times, although it is only defined once. Iterative control structures are another mechanism for executing the same statements many times.

Consider the sequence of Fibonacci numbers, in which each number is the sum of the preceding two:

0, 1, 1, 2, 3, 5, 8, 13, 21, ...

Each value is constructed by repeatedly applying the sum-previous-two rule. The first and second are fixed to 0 and 1. For instance, the eighth Fibonacci number is 13.

We can use a while statement to enumerate n Fibonacci numbers. We need to track how many values we've created (k), along with the kth value (curr) and its predecessor (pred). Step through this function and observe how the Fibonacci numbers evolve one by one, bound to curr.

1def fib(n):
2    """Compute the nth Fibonacci number, for n >= 2."""
3    pred, curr = 0, 1   # Fibonacci numbers 1 and 2
4    k = 2               # Which Fib number is curr?
5    while k < n:
6        pred, curr = curr, pred + curr
7        k = k + 1
8    return curr
9
10result = fib(8)
Step 2 of 25
line that has just executed

next line to execute

Global
fib
 
func fib(n)

Remember that commas seperate multiple names and values in an assignment statement. The line:

pred, curr = curr, pred + curr

has the effect of rebinding the name pred to the value of curr, and simultanously rebinding curr to the value of pred + curr. All of the expressions to the right of = are evaluated before any rebinding takes place.

This order of events -- evaluating everything on the right of = before updating any bindings on the left -- is essential for correctness of this function.

A while clause contains a header expression followed by a suite:

while <expression>:
    <suite>

To execute a while clause:

  1. Evaluate the header's expression.
  2. If it is a true value, execute the suite, then return to step 1.

In step 2, the entire suite of the while clause is executed before the header expression is evaluated again.

In order to prevent the suite of a while clause from being executed indefinitely, the suite should always change some binding in each pass.

A while statement that does not terminate is called an infinite loop. Press <Control>-C to force Python to stop looping.

Video