How to make Fibonacci Series using recursion in Python.

Fibonacci Series

Q) What is a Fibonacci Series ?
0 1 1 2 3 5 8 13 21 34....

Explanation - 
  • the 2 is found by adding the two numbers before it (1+1)
  • the 3 is found by adding the two numbers before it (1+2),
  • the 5 is (2+3),
  • and so on!
If you are interested to see the longer list -
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, ...

Question -
Given a number n, print n-th Fibonacci Number ?
Explanation -
We have to solve it through recursion.
  • The program will start from Line no. 9 , it will take an input n (integer). (Let's take n= 5)
  • Then the cursor will move to Line no. 10 for loop i.e for i in range ( 1,6 ).
  • Loop will run 5 times storing value 1 2 3 4 5 in consecutive loop.
  • First, it will store value 1 i.e. i=1, and when we print(fb(1)), the cursor will move to Line No. 1 ( where our function define). Then it will move to conditional statements (if - else - elif ). First, if statement i.e. n==1, and it is true because when we put i==1,it will pass in function definition as n==1. So, it will return 1. 
  • Next for i==2 i.e. n==2, when it check if statement , it found False and the cursor will move in next condition statement i.e. elif, elif n==2 (True), return 1.
  • And for next , i==3, the cursor will shift towards else statement and return what is in it's indentation i.e. return fb(n-1)+fb(n-2). But our n==3, so fb(2)+fb(1). fb(2) not define in any conditional statement, so it will again moved to Line No. 1 where function defines. When the elif statement seems True (n==2) it will return 1 and fb(1) in if statement return  0, and there sum fb(2)+fb(1) equal to 1.
  • For the next loop n==4, it will return fb(3)+fb(2) and again the function runs like a recursion. For fb(3) it will moved to else statement and converted to fb(2) and in next recursion elif statement comes True and it returns 1. And final outcome is sum of preciding 2 no. 1+1 = 2.
  • And the loop runs so on..

Recommended Video 




Comments

Popular posts from this blog

Arithmetic Operators in Python

if - else statements in Python

print (Hello world) program in Python