Problem: Write a python program to print Fibonacci Series using loop or recursion.

Fibonacci series is that number sequence that starts with 0 followed by 1 and the rest of the following nth term is equal to (n-1)th term + (n-2)th term.

Example: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 …

Recommended:

Fibonacci Series in Python using For Loop

We need to follow the following steps in order to print the Fibonacci series in Python:

  1. Input the number of terms in the Fibonacci Series (n).
  2. If (n==1) then print 0, else if (n==2) print 0 and 1.
  3. else print 0, 1, and loop from 2 to n and print the rest of the terms by summing up the last two Fibonacci terms.
n = int(input("Enter the number of terms: "))

if n == 1:
    print("0")
elif n == 2:
    print("0, 1");
else:
    a=0
    b=1
    c=0
    
    #print the first two elements
    print("{}, {}, ".format(a,b), end='')
    #print the rest of the follwing elements
    for i in range(2,n):
        c=a+b
        print("{}, ".format(c), end='')
        a=b
        b=c

Output:

Enter the number of terms: 10
0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Fibonacci Series in Python using Recursion

Using recursion we can only get the nth Fibonacci number at a time, therefore we need to call the recursive function for every Fibonacci term.

#recusrive function returns the nth fibonacci term
def fibonacci(n):
    if n==1:
        return 0
    elif n==2:
        return 1
    
    return fibonacci(n-1)+fibonacci(n-2)
    
n = int(input("Enter the number of terms: "))

#print the rest of the follwing elements
for i in range(1,n+1):
    print("{}, ".format(fibonacci(i)), end='')

Output:

Enter the number of terms: 10
0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Leave a Reply