Write a program to Display Fibonacci Sequence Using Recursion in Python
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Python program to display the Fibonacci sequence up to n-th term using recursive functions def recur_fibo(n): """Recursive function to print Fibonacci sequence""" if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) #to take input from the user nterms = int(input("How many terms? ")) # check if the number of terms is valid if nterms <= 0: print("Plese enter a positive integer") else: print("Fibonacci sequence:") for i in range(nterms): print(recur_fibo(i)) |
This Python program displays the Fibonacci sequence up to a certain number of terms using a recursive function.
The program defines a function recur_fibo(n)
that takes a single argument, n
, and returns the n-th term of the Fibonacci sequence. The function uses a recursive approach, where it calls itself multiple times with different argument values. If the value of n
is 0 or 1, the function returns n
, as these are the base cases. Otherwise, the function returns the sum of the (n-1)th term and the (n-2)th term of the Fibonacci sequence by calling the recur_fibo()
function recursively.
The main program prompts the user to enter the number of terms and assigns it to the variable nterms
. It then uses a for loop to iterate through the range of numbers from 0 to nterms
, and in each iteration, it calls the recur_fibo(i)
function with the current value of i
as the argument and prints the result.
For example, if the user enters the number of terms 11
, the output would be: