Fibonacci Series in Python

02 Jun 2024
Beginner
504 Views

Fibonacci Sequence

The Fibonacci sequence is a series of elements where, the previous two elements are added to get the next element, starting with 0 and 1. The numbers in the Fibonacci sequence are known as Fibonacci numbers.

In this Python tutorial, we'll learn various methods to calculate the nth term and print the Fibonacci series in Python.

Fibonacci Sequence Formula

The Fibonacci formula is used to find the nth term of the sequence when its first and second terms are given. The nth term of the Fibonacci Sequence is represented as Fn. We can calculate the nth term of the Fibonacci series using the following recursive formula,

``````
Fn = Fn-1 + Fn-2
``````

where,

• n > 1
• The first term is 0 i.e., F0 = 0
• The second term is 1 i.e., F1 = 1

Calculation of the nth term of the Fibonacci Series in Python

1. Using a while loop

``````
nterms = 8

# first two terms
n1, n2 = 0, 1
count = 0

# check if the number of terms is valid
if nterms <= 0:

elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)

# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1   ``````

In the above code, the variable "nterms" stores the number of terms. We initialize the first term to 0 and the second term to 1. If nterms is greater than 2, we use a while loop in Python to find the next term in the sequence by adding the preceding two terms. Afterward, we interchange the variables and the process continues.

Output

``````Fibonacci sequence:
0
1
1
2
3
5
8
13   ``````

2. Using for Loop

``````
num = 8
n1, n2 = 0, 1
print("Fibonacci Series:")
print(n1)
print(n2)
for i in range(2, num):
n3 = n1 + n2
n1 = n2
n2 = n3
print(n3)

print()
``````

Output

``````Fibonacci Series:
0
1
1
2
3
5
8
13
``````

3. Using Recursion

``````
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = 8

# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
``````

The above code uses a recursive function recur_fibo() to calculate the nth term of the sequence. We use a for loop to iterate and calculate each term recursively.

Output

``````Fibonacci sequence:
0
1
1
2
3
5
8
13   ``````
 Read More: Recursion in Data Structures

4. Using Dynamic Programming

In this technique, we store already computed terms in a lookup table. Before adding any term, we check if it exists in the lookup table. This avoids recomputing the words and makes the algorithm faster.

``````
def fibonacci(n):
# Initialize a list to store Fibonacci numbers up to n
fib_cache = [0, 1] + [None] * (n - 1)

# Iterate through the list, calculating Fibonacci numbers on demand
for i in range(2, n + 1):
if fib_cache[i] is None:
fib_cache[i] = fib_cache[i-1] + fib_cache[i-2]

return fib_cache[n]

for i in range(10):
print(fibonacci(i), end=" ")
``````

We initialize a dictionary memo to store the Fibonacci numbers. The function first checks if the term already exists in a memo before computing it.

Output

``````0 1 1 2 3 5 8 13 21 34
``````

5. Using Caching

The Python lru_cache decorator can cache and reuse previously computed Fibonacci terms.

``````
from functools import lru_cache

@lru_cache(maxsize=1000)
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)

def main():
print("Fibonacci series:")
for i in range(8):  # Adjust the range according to your desired number of terms
print(fib(i), end=" ")

if __name__ == "__main__":
main()
``````

The above program defines the fib function to recursively generate the Fibonacci series up to the nth term using memoization with the @lru_cache decorator.

Output

``````Fibonacci series:
0 1 1 2 3 5 8 13
``````

6. Using Backtracking

Backtracking is not an efficient approach for generating the Fibonacci Series because it involves exploring all possible paths in the search space. It can lead to unnecessary computations exploring irrelevant paths.

Practical Examples and Use Cases of the Fibonacci Series in Python

• Algorithm Optimization: The Fibonacci series helps in teaching recursion and dynamic programming techniques.
• Mathematical Modeling: Fibonacci numbers often appear in mathematical modeling and analysis, such as in the study of population growth, the golden ratio, etc.
• Numerical Analysis: Fibonacci numbers are used in numerical analysis for approximating solutions to various mathematical problems, including optimization and root finding.
• Computer Graphics: Fibonacci sequences are employed in computer graphics and visual effects to generate patterns, textures, and animations.
• Algorithm Design: Fibonacci numbers can be used as inputs or constraints in the design and analysis of algorithms, such as in sorting, searching, and graph traversal algorithms.
• Data Compression: Fibonacci codes are used in data compression techniques to encode integer sequences efficiently.
• Cryptography: Fibonacci numbers can be utilized in cryptographic algorithms to generate secure keys and random sequences.

Summary

In this tutorial, we saw various methods to generate the Fibonacci series in Python. Every method has its associated advantages and disadvantages. To understand the application of any method depends on practice. The more you practice the more your concepts get furnished.

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
 Microsoft Azure Cloud Architect Aug 11 SAT, SUN Filling Fast03:00PM to 05:00PM (IST) ASP.NET Core Certification Training Aug 11 SAT, SUN Filling Fast09:30AM to 11:30AM (IST) Full-Stack .NET Developer Certification Training Aug 18 SAT, SUN Filling Fast08:30PM to 10:30PM (IST) ASP.NET Core Certification Training Aug 23 MON, WED, FRI Filling Fast07:00AM to 08:30AM (IST) ASP.NET Core Project Aug 24 SAT, SUN Filling Fast07:00AM to 09:00AM (IST) React Certification Training Aug 25 SAT, SUN Filling Fast06:00PM to 08:00PM (IST) Advanced Full-Stack .NET Developer Certification Training Sep 01 SAT, SUN Filling Fast08:30PM to 10:30PM (IST) ASP.NET Core Certification Training Sep 01 SAT, SUN Filling Fast08:30PM to 10:30PM (IST) .NET Microservices Certification Training Sep 08 SAT, SUN Filling Fast05:30PM to 07:30PM (IST) .NET Solution Architect Certification Training Sep 08 SAT, SUN Filling Fast05:30PM to 07:30PM (IST)

Can't find convenient schedule? Let us know