The Fibonacci sequence is a well-known sequence in mathematics that begins with 0 and 1 and each subsequent number in the sequence is the sum of the previous two numbers.
This sequence can be calculated using recursion in Python.
Recursion is a programming technique where a function calls itself to solve a problem.
In the case of the Fibonacci sequence, we can use recursion to calculate the nth term of the sequence.
To display the Fibonacci sequence using recursion in Python, we need to define a function that takes a number n as input and returns the nth term in the sequence.
The function will call itself recursively to calculate the previous two terms in the sequence and then add them together to get the current term.
Here’s the Python program to display the Fibonacci sequence using recursion:
def fibonacci(n): if n <= 1: return n else: return (fibonacci(n-1) + fibonacci(n-2)) nterms = int(input("Enter the number of terms: ")) if nterms <= 0: print("Please enter a positive integer") else: print("Fibonacci sequence:") for i in range(nterms): print(fibonacci(i))
In this program, we first define the
fibonacci function that takes a number
n as input.
n is less than or equal to 1, the function simply returns
Otherwise, the function calls itself recursively with
n-2 as inputs, adds the results together, and returns the sum.
Next, we ask the user to input the number of terms they want to display in the Fibonacci sequence.
If the input is less than or equal to 0, we print an error message.
Otherwise, we print the Fibonacci sequence by calling the
fibonacci function for each term in the range of 0 to
In conclusion, this Python program uses recursion to calculate and display the Fibonacci sequence.
Recursion is a powerful programming technique that can be used to solve a wide range of problems, including the calculation of mathematical sequences like the Fibonacci sequence.