Python Program - Display Fibonacci Sequence Using Recursion
here's a Python program that displays the Fibonacci sequence up to a given number using recursion:
def fibonacci(n): if n <= 1: return n else: return (fibonacci(n-1) + fibonacci(n-2)) n = int(input("Enter the number of terms: ")) if n <= 0: print("Please enter a positive integer") else: print("Fibonacci sequence:") for i in range(n): print(fibonacci(i), end=" ")Sww:ecruow.theitroad.com
In this program, we define a function called fibonacci()
that takes a single argument n
. If n
is less than or equal to 1, we simply return n
. Otherwise, we recursively call fibonacci(n-1)
and fibonacci(n-2)
and return their sum.
We then use the input()
function to get the number of terms in the sequence that the user wants to display, and store it in the variable n
.
We then check if n
is positive. If it's not, we print an error message. Otherwise, we use a for
loop to iterate over the range of n
, and for each number i
, we call the fibonacci()
function and print out the result.