π Day 94/150 – Recursive Fibonacci in Python
The Fibonacci sequence is one of the most popular examples used to understand recursion. In this sequence, each number is the sum of the two preceding numbers.
Fibonacci Sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, ...
In this post, we'll explore four different ways to generate Fibonacci numbers using recursion and related approaches.
Method 1 – Basic Recursive Function
A recursive function calls itself to calculate the Fibonacci number.
def fibonacci(n): if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(6))
Output
8
Explanation
-
If n is 0 or 1, the function returns n.
- Otherwise, it returns the sum of the previous two Fibonacci numbers.
- The function keeps calling itself until it reaches the base case.
Method 2 – Taking User Input
Calculate the Fibonacci number recursively using user input.
7def fibonacci(n): if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2) num = int(input("Enter the position: ")) print("Fibonacci Number:", fibonacci(num))
Sample Input
Output
Fibonacci Number: 13Explanation
- The user enters the position in the Fibonacci sequence.
- The recursive function calculates the Fibonacci number at that position.
- The result is displayed.
Method 3 – Print Fibonacci Series Using Recursion
Print the first n Fibonacci numbers recursively.0 1 1 2 3 5 8def fibonacci(n): if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2) terms = 7 for i in range(terms): print(fibonacci(i), end=" ")
Output
Explanation
- The for loop calls the recursive function for each position.
- Each Fibonacci number is printed in sequence.
- This generates the first terms Fibonacci numbers.
Method 4 – Recursive Function with Error Handling
Handle invalid input such as negative numbers.
Position cannot be negative.def fibonacci(n): if n < 0: return "Position cannot be negative." if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(-5))
Output
Explanation
- The function first checks whether the position is negative.
- If it is, an error message is returned.
- Otherwise, recursion proceeds normally.
Comparison of Methods
| Method | Best For |
|---|---|
| Basic Recursion | Learning recursion |
| User Input | Interactive programs |
| Recursive Series | Printing multiple Fibonacci numbers |
| Error Handling | Validating user input |
π₯ Key Takeaways
- The Fibonacci sequence is a classic example of recursion.
- Every recursive function must include a base case to stop recursive calls.
- Recursive Fibonacci is easy to understand but inefficient for large values because it repeats calculations.
- Input validation helps prevent invalid recursive calls.
- For large Fibonacci numbers, iterative or dynamic programming approaches are more efficient than recursion.


0 Comments:
Post a Comment