Sep 2

Lecture Overview

term = int(input("Compute which Fibonacci number? "))
if term == 0:
    print(0)

elif term == 1:
    print(1)

else:
    f_prev = 0
    f_current = 1
    i = 1
    while i < term:
        temp = f_current + f_prev
        f_prev = f_current
        f_current = temp
        i = i + 1
    print(f_current)

First, the code above is a single if-elif-else statement with three blocks (note the indentation). Only one of these three blocks will be executed depending on the term variable. The first two blocks are straightfoward. Let's look at the third block. Before the while loop we set up three variables.

Initially we set up i = 1, f_current = 1 and f_prev = 0. That means we have currently computed the 1st Fibonacci number which is stored in f_current and the previous Fibonacci number is in f_prev. We now will loop until we have computed the termth Fibonacci number. So while i < term we will repeatedly execute the indented block (four statements) under the while statement. These four statements are called the body of the loop.

The body first computes the next (i+1)st Fibonacci number and stores it in temp. It then updates f_current and f_prev so that they hold the (i+1)st Fibonacci number and the ith Fibonacci number and finally increments i by one. Thus after the body of the loop has completed, i is one larger and f_current and f_prev still hold the ith Fibonacci number and (i-1)th Fibonacci number. We execute the body of the loop repeatedly until i == term when we print the result.

Exercises

Edit the above code to compute the Lucas Numbers instead of the Fibonacci numbers.