TLDR; In post we are going to learn how to create a fibonacci series program using recursion in python. If you are looking for code only, you can find it Here
Fibonacci series
Explanation
The Fibonacci series is the special sequence of numbers in which next number is calculated using a formulae. first two numbers are default 0 and 1. Formula is n2 = n1 + n0
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
The next number is calculated by the above written formula. Below is the explanation of above series.
- Third number is sum of first and second i.e 0 + 1 = 1
- Fourth number is sum of second and third i.e 1 + 1 = 2
- Fifth number is sum of third and fourth i.e 1 + 2 = 3
- Sixth number is sun of fourth and fifth i.e = 5
- and same goes for next numbers.
Architecture
Programming is subject where there are more than one way to tackle a problem, and one problem can have multiple solutions. The same applies to this problem.
We have few approaches to conquer this problem. One of them is recursion. We will use recursion to tackle this problem this time.
- First we will create a recursive function which will accept 3 arguments n(number of terms left to print), a1(first number), a2(second number).
- Check for number of terms left (n) to calculate. If it is 1 or less than 1 we will print the first number (a1) and return out of function. Also this is our break condition of this recursive function.
- If number is failing the above check then we will calculate next number and pass these arguments to this recursive function (n-1, a2, a1 + a2).
- Now we will call this recursive function inside our main function (in python it is not necessary to use a main function).
Code
terms = int(input("how many terms? : ")) #getting input from the user
#using recursion to print the series
def recur_fibo(n,a1,a2):
if n <= 1:
#return this if terms is less than 1
print(a1)
return
else:
print(str(a1) , end=" , ")
return(recur_fibo(n-1,a2,a1 + a2))
#checking for the negative number and single terms
if terms <= 0:
print("Please enter a positive integer")
elif terms == 1:
print("Fibonacci Sequence of 1 terms : ")
print(0)
else:
recur_fibo(terms,0,1)
We need to be careful about the indentation of loops and functions in python. If any error comes please match your program’s indentation with below screenshot carefully.
Code output
And here comes the end of the post. If you have any comments or suggestions please leave them below.
Thanks for reading this far.
Happy coding. bye