Python program that uses recursion to display the Fibonacci sequence up to a given number:

Created with Sketch.

Python program that uses recursion to display the Fibonacci sequence up to a given number:

def fibonacci(n):
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    else:
        fib_list = fibonacci(n-1)
        fib_list.append(fib_list[-1] + fib_list[-2])
        return fib_list

n = int(input("Enter the number of terms: "))
print(fibonacci(n))

The fibonacci() function takes a single argument, n, which represents the number of terms in the sequence to be displayed. The function uses recursion to calculate the terms of the Fibonacci sequence. The base case for the recursion is when n is less than or equal to 0, in which case an empty list is returned. If n is 1, the function returns a list containing the single value 0, and if n is 2, the function returns a list containing the values 0 and 1. In all other cases, the function calls itself with the argument n-1, and then appends the sum of the last two elements of the resulting list to that list, before returning it.

The input() function is used to prompt the user to enter the number of terms in the sequence to be displayed, and the resulting value is converted to an integer using the int() function. The print() function is then used to display the resulting list of Fibonacci numbers.

Leave a Reply

Your email address will not be published. Required fields are marked *