Exercise
Calculating Fibonacci Sequence With A Function
Objective
Develop a Python program that uses a recursive function to determine a number in the Fibonacci sequence. In this series, the first two numbers are 1, and each subsequent number is the sum of the previous two.
For example, you could use it like this: print(fibonacci(5))
Example Python Exercise
Show Python Code
# Define the recursive function to calculate the Fibonacci number
def fibonacci(n):
# Base case: if n is 1 or 2, return 1 (the first two numbers in the Fibonacci sequence)
if n == 1 or n == 2:
return 1
# Recursive case: return the sum of the previous two Fibonacci numbers
else:
return fibonacci(n - 1) + fibonacci(n - 2)
# Main function to test the fibonacci function
def main():
# Test the fibonacci function with n = 5
print(fibonacci(5)) # Expected output: 5
# Call the main function to execute the program
main()
Output
5
Share this Python Exercise