How to generate Fibonacci series of n terms in python / Various methods to print Fibonacci series of n items in python

What is Fibonacci series?
A Fibonacci series is a sequence of numbers where each number is a sum of previous 2 numbers. First two terms of a Fibonacci series are 0 and 1.


Method 1: Iterative Approach
This approach is based on the following algorithm
1. Declare two variables representing two terms of the series. Initialize them to 0 and 1 as the first and second terms of the series respectively.
2. Initialize a variable representing loop counter to 0.
3. Loop from 0 to the total number of terms in the series.
4. In every iteration,
   A. add the variables defined in step 1. This represents a term(or item) of the Fibonacci series.
   B. assign the value of second variable to first and the sum in above step A to the second variable.
Code written as per the above algorithm follows.

# read the total number of items in Fibonacci series
max_item_input = input("Enter the number of items in Fibonacci series\n")
max_item = int(max_item_input)
# variables to hold two items of series
first = 0
second = 1
# loop counter
item = 0
# iterate till the total number of items in the series
while item < max_item:
    # add two terms, the result represents the subsequent element of the series
    sum = first + second
    # print current item
    print(first,end = ",")
    # assign variables
    first = second
    second = sum
    # increment loop counter
    item += 1

Enter the number of items in Fibonacci series
6
0,1,1,2,3,5,


Method 2: Using recursion
Create a recursive function which receives an integer as argument. This integer argument represents the position in Fibonacci series and returns the value at that position. Thus, if it receives 5, it returns the value at 5th position in Fibonacci series.
This recursive function returns 0 and 1 if the argument value is 0 or 1. For all other values it calls itself with the sum of nth and (n-1)th positions.
The program reads the total number of elements in Fibonacci series from keyboard. It then initiates a loop starting from 0 till this input value. In every iteration, the recursive function is called and the resultant Fibonacci item for that position is printed.

def fibonacci(number):
    # return 0 and 1 for first and second terms
    if number == 0:
        return 0
    elif number == 1:
        return 1
    else:
        # return the sum of two numbers
        return fibonacci(number - 1) + fibonacci(number - 2)
 
# read the total number of items in Fibonacci series
max_item_input = input("Enter the number of items in Fibonacci series\n")
max_item = int(max_item_input)
 
# iterate from 0 till number of terms
for count in range(max_item):
    print(fibonacci(count), end=",")

Output of above execution is

Enter the number of items in Fibonacci series
8
0,1,1,2,3,5,8,13,

Please share your thoughts on this post in the comment section below. Keep visiting!!!

Mark Your Impression

Close Menu