Search⌘ K
AI Features

Solution Review: Implementing the Fibonacci Series

Explore the implementation of the Fibonacci series in Python. Learn to handle edge cases, use loops effectively, and understand the logic behind generating Fibonacci numbers from basic program structures.

We'll cover the following...

Solution

Python 3.5
def fib(n):
# The first and second values will always be fixed
first = 0
second = 1
if n < 1:
return -1
if n == 1:
return first
if n == 2:
return second
count = 3 # Starting from 3 because we already know the first two values
while count <= n:
fib_n = first + second
first = second
second = fib_n
count += 1 # Increment count in each iteration
return fib_n
n = 7
print(fib(n))

Explanation

The first thing we need to do is handle all the edge cases. At line 6, if n is less than 1, we simply have to return -1.

From ...