The Fibonacci Series in Python

What is the output of this code snippet?

 

# Fibonacci series:
a, b = 0, 1
while b < 5:
    print(b)
    a, b = b, a+b

 

The Fibonacci series was discovered by the Italian mathematician Leonardo Fibonacci in 1202 and even earlier by Indian mathematicians. The series appears in unexpected areas such as economics, mathematics, art, and nature.

In the puzzle, we give a simple algorithm to calculate the Fibonacci numbers. The series starts with the Fibonacci numbers zero and one. The algorithm calculates the next element of the series as the sum of both last elements. For this, the algorithm has to keep track only of the last two elements in the series. Thus, we maintain two variables a and b, being the second last and last element in the series, respectively.
This computation repeats until the while condition evaluates to False, i.e., until b>=5.

For clarity of the code, we used the language feature of multiple assignments in the first and the last line.
This feature works as follows. On the left-hand side of the assignment, there is any sequence of variables such as a list or a tuple. On the right-hand side of the assignment, we specify the values to be assigned to these variables. Both sequences on the left and on the right must have the same length. Otherwise, the Python interpreter will throw an error.

Note that all expressions on the right-hand side are first evaluated before they are assigned. This is an important property for our algorithm. Without this property, the last line would be wrong as expression a+b would consider the wrong value for a.


Are you a master coder?
Test your skills now!

 

Related Video

Solution

1
1
2
3

 

Leave a Comment