Python Tutorial (33) – Example: Using recursive Fibonacci sequence

Time: Column:Python views:218

Python Code to Generate Fibonacci Sequence Using Recursion

The following code demonstrates how to generate a Fibonacci sequence using a recursive function in Python.

Example: Recursive Fibonacci Sequence

# Define the recursive function to generate Fibonacci sequence
def recur_fibo(n):
   """Recursive function to return Fibonacci sequence"""
   if n <= 1:
       return n
   else:
       return(recur_fibo(n-1) + recur_fibo(n-2))

# Get user input
nterms = int(input("How many terms would you like to display? "))

# Check if the input is valid
if nterms <= 0:
   print("Please enter a positive integer")
else:
   print("Fibonacci sequence:")
   for i in range(nterms):
       print(recur_fibo(i))

Sample Output:

How many terms would you like to display? 10
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34

This code uses a recursive function to generate and print the Fibonacci sequence for the number of terms specified by the user. The result shows the first 10 numbers in the Fibonacci sequence.