Recursive Fibonacci
Intermediate · Write the code · from Python Recursion: How It Works, When to Use It, and Examples
From the lesson: Python Recursion: How It Works, When to Use It, and Examples
Imagine a set of Russian nesting dolls. You open the biggest one and find a smaller one inside. Open that, and there's an even smaller one. You keep opening until you reach the tiniest doll that doesn't open - that's the end.
Read the lessonWrite a recursive function called fibonacci that returns the nth Fibonacci number.
The Fibonacci sequence starts: 0, 1, 1, 2, 3, 5, 8, 13, ...
Rules:
fibonacci(0) returns 0fibonacci(1) returns 1fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)Print the results for n = 0, 1, 5, and 10 on separate lines.
def fibonacci(n):
# Your code here
pass
print(fibonacci(0))
print(fibonacci(1))
print(fibonacci(5))
print(fibonacci(10))
More Recursion exercises
- Predict Recursive OutputBeginner
- Recursive Sum 1 to NBeginner
- Fix the Broken Power FunctionIntermediate
- Reverse a String RecursivelyIntermediate
- Count Digits RecursivelyAdvanced
All Python exercises · 50 practice problems · Functions quiz