Fibonacci series in Python with recursion
In this post, you'll learn how to display the Fibonacci sequence using a recursive function in the Python programming language.
The Fibonacci series are the sequence of numbers in which the next number is the sum of the previous two numbers. The Fibonacci series was known hundreds of years earlier. The "Fibonacci" name came from the nickname "Bonacci".
We can easily remember the Fibonacci Sequence using November 23rd as the Fibonacci Day. As November 23rd has the digits "1, 1, 2, 3", which is part of the sequence.
In the above image, the first two numbers are 0 and 1. So, according to the Fibonacci rule, the third number is 1 (sum of 0 and 1). The fourth number is 2, and so on.
0 + 1 = 1 // 0, 1, 1
1 + 1 = 2 // 0, 1, 1, 2
1 + 2 = 3 // 0, 1, 1, 2, 3
2 + 3 = 5 // 0, 1, 1, 2, 3, 5
0 ,1 , 1, 2, 3, 5, 8, 13, 21, 34....
Python Fibonacci Series Program
Recursion function is a function that is called by itself. In the given example, we call the recursion function to get the Fibonacci series. A recursion function continues until some condition is met to prevent it. That's why we use the if else statement to break the infinite recursion.
def fibonacci_recur(n):
if n <= 1:
return n
else:
return(fibonacci_recur(n-1) + fibonacci_recur(n-2))
# take input from the user
series = int(input("How many number of series? "))
# check the valid input
if series <= 0:
print("Invalid: Plese enter a positive integer")
else:
print("Fibonacci of ",series," is :")
for i in range(series):
print(fibonacci_recur(i))
Output of the above code -
How many number of series? 15
Fibonacci of 15 is :
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
Python Find nth Fibonacci Number
def fibonacci_recur(n):
if n <= 1:
return n
else:
return(fibonacci_recur(n-1) + fibonacci_recur(n-2))
# take input
num = int(input('Enter number of terms: '));
# check the valid input
if num <= 0:
print("Invalid: Plese enter a positive integer")
else:
print("Fibonacci of ",num,": ",fibonacci_recur(num))
Output of the above code:
Enter number of terms: 9
Fibonacci of 9 : 34
Enter number of terms: 12
Fibonacci of 12 : 144
Related Articles
Add background image in Python Tkinter
Reverse pyramid pattern in Python
Python program to list even and odd numbers of a list
Python program to print all even numbers between 1 to 100
Sum of n numbers in python using for loop
Python program to multiply two numbers
Python program to map two lists into a dictionary
Fizzbuzz program in Python
Python split string by comma
Python alive progress bar
Python progress bar tqdm
Python language translator code
Python take screenshot of specific window
Web scraping Python BeautifulSoup
Reverse a number in Javascript
HTML open link in new tab
Python print without newline
Python iterate list with index
Python add list to list
Python random choice
Python dict inside list
Remove character from string Python
Python raise keyword