Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is the Fibonacci Series in Python?
3.
Different Methods to Print Fibonacci Series in Python
4.
Method 1: Python Program for Fibonacci numbers Using Recursion
4.1.
Implementation
4.2.
Python
4.3.
Time complexity 
4.4.
Space complexity
5.
Method 2: Fibonacci Series Program Using Dynamic Programming
5.1.
Implementation
5.2.
Python
5.3.
Time complexity 
5.4.
Space complexity
6.
Method 3: Fibonacci Sequence Using While Loop
6.1.
Implementation
6.2.
Python
6.3.
Time complexity 
6.4.
Space complexity
7.
Method 4: Fibonacci Sequence Python Using Cache
7.1.
Implementation
7.2.
Python
7.3.
Time complexity 
7.4.
Space complexity
8.
Applications of Fibonacci Series in Python
9.
Frequently Asked Questions
9.1.
What is the Fibonacci series in Python?
9.2.
How do you add a Fibonacci series to a list in Python?
9.3.
How do you write Fibonacci series in Python by recursion?
9.4.
How do you solve Fibonacci for loop?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Fibonacci Series Program in Python

gp-icon
Basics of Python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

The Fibonacci series in Python is a sequence of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1. It is widely used in programming and mathematics for its recursive nature and applications in various algorithms.

Fibonacci Series Program in Python

What is the Fibonacci Series in Python?

Fibonacci series is a sequence of numbers where starting from the third element, each element is the sum of the previous two elements. The Fibonacci series starts with 0 and 1. Therefore, the sequence is as follows: 0, 1, 1, 2, 3, 5, 8, 13, etc.

It is a series of numbers that starts from 0 and 1 and then continues by adding the preceding two numbers. 

In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the function, 

  Fn = Fn-1 + Fn-2


With the initial two terms' values,

  F0 = 0 and F1 = 1 

The Fibonacci series has many interesting properties and is found in various aspects of mathematics. There are many ways to generate a Fibonacci sequence containing N elements in Python.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Different Methods to Print Fibonacci Series in Python

  • Method 1: Using Recursion
     
  • Method 2: Using Dynamic Programming
     
  • Method 3: Using While Loop
     
  • Method 4: Cache

Method 1: Python Program for Fibonacci numbers Using Recursion

Recursion is the primary programming technique in which a function or algorithm calls itself directly or indirectly until a specified condition is met. Let’s see how to use recursion to print the first ‘n’ numbers of the Fibonacci Series in Python.

The function “fibonacciSeries” is called recursively until we get the output. We first check whether the Number is zero or one in the function. If yes, we return the value of the Number. If not, we recursively call Fibonacci with the values Number-1 and Number-2.

Implementation

  • Python

Python

# Python program to generate Fibonacci series Program using Recursion
def fibonacciSeries(Number):
if Number == 0:
return 0
elif Number == 1:
return 1
else:
return fibonacciSeries(Number - 1) + fibonacciSeries(Number - 2)


n = int(input())
print("Fibonacci series:", end=' ')
for n in range(0, n):
print(fibonacciSeries(n), end=' ')

 

Input:

6

 

Output:

Fibonacci Series: 0 1 1 2 3 5

Recurrence Relation = T(n) = T(n-1) + T(n-2).

Time complexity 

The time complexity for this program is O(2n)

Space complexity

The space complexity for this program is O(n)

Method 2: Fibonacci Series Program Using Dynamic Programming

We can also use Dynamic Programming to print the Fibonacci Series in Python. The first two fixed values of the Fibonacci series are 0 and 1. We start our loop from the second index and try to append the values in the loop using the previous two numbers.

Implementation

  • Python

Python

# fibonacci series in python using dynamic programming
def fibonacci(n):
# Taking 1st two fibonacci numbers as 0 and 1
f = [0, 1]
for i in range(2, n+1):
f.append(f[i-1] + f[i-2])
return f


n = int(input())
ans = fibonacci(n)
for n in range(0, n):
print(ans[n], end=' ')


Input:

5


Output:

0 1 1 2 3

Time complexity 

The time complexity for this program is O(n)

Space complexity

The space complexity for this program is O(n)

Method 3: Fibonacci Sequence Using While Loop

The last approach we will be discussing is using a while loop. We will use some basic conditions to print the Fibonacci series. As we already know, the first two numbers of the Fibonacci series are 0 and 1 by default. Input the number of values we want to generate the Fibonacci sequence and initialize a=0, b=1, sum=0, and count=1. Start a while loop using the condition count<=n and print the sum every time the condition works. Increment the count variable, swap ‘a’ and ‘b,’ and store the addition of a and b in the sum. If count>n, the condition fails, and the algorithm ends.

Implementation

  • Python

Python

# Python program to generate Fibonacci series based on n value
n = int(input())
a = 0
b = 1
sum = a + b
count = 1
print("Fibonacci series is: ", end=" ")
while (count <= n):
count += 1
print(a, end=" ")
a = b
b = sum
sum = a + b


Input:

3


Output:

Fibonacci series is:  0 1 1

Time complexity 

The time complexity for this program is O(n)

Space complexity

The space complexity for this program is O(1)

Method 4: Fibonacci Sequence Python Using Cache

In this code, a dictionary cache is used to store previously computed Fibonacci numbers so that they can be retrieved from the cache instead of being recomputed every time the function is called. When the function is called with a value of n, it first checks if the result has already been computed and stored in the cache. If it has, the cached value is returned. Otherwise, the function computes the Fibonacci number using the recursive formula fibonacci(n-1) + fibonacci(n-2), stores the result in the cache, and returns the result.

Implementation

  • Python

Python

cache = {}  # Cache to store previously computed Fibonacci numbers

def fibonacci(n):
if n <= 1:
return n
elif n in cache:
return cache[n]
else:
result = fibonacci(n-1) + fibonacci(n-2)
cache[n] = result # Store the result in cache for future use
return result

n = int(input())
for i in range(0, n):
print(fibonacci(i), end=' ')


Input:

3


Output:

0 1 1

Time complexity 

The time complexity for this program is O(n)

Space complexity

The space complexity for this program is O(n)

Applications of Fibonacci Series in Python

Applications of the Fibonacci series in Python include:

  1. Mathematics: It's used in mathematical research, number theory, and the study of patterns and sequences.
     
  2. Algorithms: Fibonacci numbers are the basis for various algorithms such as dynamic programming, memoization, and matrix exponentiation.
     
  3. Optimization: Fibonacci sequences help optimize search algorithms, data structures, and time complexity in algorithms.
     
  4. Financial Modeling: In finance, Fibonacci numbers are applied in modeling market trends, calculating investment strategies, and analyzing stock prices.
     
  5. Graphics and Visualization: Fibonacci patterns are used in generating visually appealing designs, animations, and graphics.
     
  6. Natural Sciences: Fibonacci sequences appear in nature, including the arrangement of leaves on a stem, the branching of trees, and the spirals of shells and flowers.
     

Also Read - Multilevel Inheritance in Python

Frequently Asked Questions

What is the Fibonacci series in Python?

It is a sequence of integers 0, 1, 1, 2, 3, 5... The series starts with 0 and 1. All other terms are obtained by adding the last two numbers of the sequence, i.e., to get the nth number, sum the (n-1)th and (n-2)th number.

How do you add a Fibonacci series to a list in Python?

To add Fibonacci series to a list in Python, iterate through the desired range and append Fibonacci numbers to the list using a loop or list comprehension.

How do you write Fibonacci series in Python by recursion?

Write Fibonacci series in Python by recursion using a function that calls itself with the previous two Fibonacci numbers.

How do you solve Fibonacci for loop?

Solve Fibonacci using a for loop by iteratively updating variables to store the sum of the previous two Fibonacci numbers within the loop.

Conclusion

In this article, we have discussed Python Program for Fibonacci numbers. We have discussed different approaches to finding the Nth Fibonacci sequence. We have also discussed its application in Python.

The different approaches we used are: Recursion, Dynamic Programming, While Loops, and Cache

Recommended Reading:

To be more confident, you need to practice more competitive programming, and there are many questions to practice in data structures and algorithms to get into top product-based companies. You can check out Coding Ninjas studio, a platform where you can explore all the previous interview questions. 

Previous article
Difference between Julia and Python
Next article
How to Find GCD of Two Numbers in Python?
Guided path
Free
gridgp-icon
Basics of Python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass