a shot of dev knowledge

Related tags

# How to implement the Fibonacci sequence in Python

The Fibonacci Sequence is the series of numbers:

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

The series starts with $0$ and $1$ as the first two numbers in the series. The next number in the series is found by summing the two numbers before it.

For example:

• The third number in the sequence, $1$, is found by adding the two numbers before it $(0+1)$.
• The fourth number in the sequence, $2$, is found by adding the two numbers before it $(1+1)$.

## Implementing the Fibonacci Sequence

Fibonacci Sequence can be implemented both iteratively and recursively in Python.

For both examples, try changing the value of the argument passed to the function to print out more numbers in the sequence.

### Iterative implementation

def fib(number_of_terms):
counter = 0

first = 0
second = 1
temp = 0

while counter <= number_of_terms:
print(first)
temp = first + second
first = second
second = temp
counter = counter + 1

# Driver Code
fib(10)

In the above implementation, The code prints the first value on each iteration of the loop. Each iteration calculates the next value by summing the previous two values and then updates the values of first and second.

### Recursive Implementation

Calculating the 6th Fibonacci number.
def fib(term):
if term <= 1:
return (term)
else:
return (fib(term-1) + fib(term-2))

# Change this value to adjust the number of terms in the sequence.
number_of_terms = 10
for i in range(number_of_terms):
print(fib(i))


The above program computes the Fibonacci value by calling itself with a lesser value several times. The termination condition for this is reached when term == 0 and term == 1.

Related tags

RELATED COURSES
View all Courses
Related Courses
Related Courses
View all Courses
Keep Exploring

Learn in-demand tech skills in half the time