Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Fibonacci Series in Python -Explained with Examples

Fibonacci Series in Python -Explained with Examples

25 Sep 2024
Beginner
2.41K Views
13 min read
Learn with an interactive course and practical hands-on labs

Free DSA Course with Certificate

Python Fibonacci Series

The Fibonacci Series ! If you're new to this term, it refers to a sequence of numbers in which each number after the first two is the sum of the two numbers before it. That seems really awesome, right?What if I told you that implementing this in Python is quite simple? Whether you're just getting started or brushing up on your Python skills, this is an excellent method to practice loops and recursion. So let's break it down and create a simple Python program to generate the Fibonacci series! Ready? Let's go!

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

Read More: Top 50 Python Interview Questions and Answers

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

In the below Python Compiler,we have implemented Fibonacci series in Python 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:
   print("Please enter a positive integer")
   
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   

Explanation

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

Here, We can also implement the Fibonacci series program in Python using for loop as shown below:

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
Read More: Python For Loop

3. Using Recursion

Yes..! you heard it right ..! We can also print the Fibonacci series in Python using recursion. Let's elaborate on this with the below example.

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))

Explanation

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 Python

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.

Calculate the sum of the Fibonacci series

Here we can calculate the sum of the Fibonacci series in Python using the following code:
def fibonacci_sum(n):
    a, b = 0, 1
    total = 0
    for _ in range(n):
        total += a
        a, b = b, a + b
    return total

n = int(input("Enter the number of terms: "))
print("Sum of Fibonacci series:", fibonacci_sum(n))

Output

Enter the number of terms: 10
Sum of Fibonacci series: 88

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. If you wanna try a new way to calculate this series you can go with to calculate the Fibonacci series in Python using range. 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 cleared. Also if you have gained interest in Python you can give it a try for Data Science with Python Course.

FAQs

Each number is equal to the sum of the preceding two numbers. For example, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181.

Fibonacci numbers are the sequence of numbers defined by the linear equation, F(n) = F(n-1) + F(n-2), for n = 3, 4, ... and F(0) = 0, F(1) = F(2) = 1. 
Share Article
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this