Python Program to Display Fibonacci Sequence Using Recursion


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

The Fibonacci Sequence is a special sequence of numbers that starts with 0 and 1, and each subsequent number in the sequence is the sum of the previous two. So, the first few numbers in the sequence are 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.


Python Code :

The below Python program displays the Fibonacci sequence up to a specified number of terms using recursion:


def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

# Prompt user for number of terms
n_terms = int(input("Enter the number of terms: "))

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

Explanation:

  1. The fibonacci() function takes an integer n as input and recursively calculates the Fibonacci number for that position in the sequence. The base case is when n is less than or equal to 1, in which case the function returns n. Otherwise, it returns the sum of the previous two Fibonacci numbers.

  2. The user is prompted to enter the number of terms they want to display.

  3. The input is checked to ensure it is a positive integer. If it is not, an error message is displayed.

  4. If the input is valid, a for loop is used to iterate through the specified number of terms and display the corresponding Fibonacci number by calling the fibonacci() function.

For Example:


Enter the number of terms: 10
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co