Write a python program to print Fibonacci Series using loop or recursion.
Fibonacci series is that number sequence which starts with 0 followed by 1 and rest of the following nth term is equal to (n-1)th term + (n-2)th term.
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.
- Input the number of terms in Fibonacci Series (
n
). - If (
n==1
) then print 0, else if (n==2
) print 0 and 1. - else print 0, 1 and loop from 2 to n and print rest of the terms by summing up the last two fibonacci terms.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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
1 2 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #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
1 2 | Enter the number of terms: 10 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 |
If you have any doubts or suggestion then comment below.