1. Introduction
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. In this tutorial, we will learn how to write a Python program to find the Fibonacci series using recursion.
A Fibonacci number is an element of the Fibonacci sequence. In mathematical terms, it's defined by the recurrence relation F(n) = F(n-1) + F(n-2) with seed values F(0) = 0 and F(1) = 1.
2. Program Steps
1. Define the nth number in the Fibonacci sequence to find.
2. Implement a recursive function that calculates Fibonacci numbers.
3. Call this function and print the nth Fibonacci number.
3. Code Program
# Function to calculate the n-th Fibonacci number using recursion
def fibonacci(n):
# Base case: return n if n is 0 or 1
if n in (0, 1):
return n
# Recursive case: return the sum of the two preceding Fibonacci numbers
return fibonacci(n-1) + fibonacci(n-2)
# Define the n-th term to find in the Fibonacci sequence
n_th_term = 10
# Calculate and print the n-th Fibonacci number
print(f"The {n_th_term}th Fibonacci number is: {fibonacci(n_th_term)}")
Output:
The 10th Fibonacci number is: 55
Explanation:
1. fibonacci is a recursive function that takes a single argument n, which is the position in the Fibonacci sequence.
2. The function includes a base case that directly returns n when n is either 0 or 1.
3. For all other values of n, the function calls itself twice to obtain the n-1 and n-2 Fibonacci numbers and adds them to find F(n).
4. n_th_term is set to 10, indicating that we want to find the 10th number in the Fibonacci sequence.
5. The function fibonacci(n_th_term) is called, and it prints the result, "The 10th Fibonacci number is: 55".
6. The output 55 is the 10th number in the Fibonacci sequence, demonstrating the successful calculation using recursion.
Comments
Post a Comment
Leave Comment