Fibonacci Series Recursively
Print Fibonacci terms by repeatedly calling a recursive function. Students separate term count from index and examine the cost of repeated branching recursion.
1def fibonacci(n):2 if n == 0:3 return 04 if n == 1:5 return 16 return fibonacci(n - 1) + fibonacci(n - 2)78# Print series9n = int(input("Enter number of terms: "))10for i in range(n):11 print(fibonacci(i), end=" ")12print()
Output
Enter number of terms: 8 0 1 1 2 3 5 8 13
In this one
- Separate a loop from its helper
- Count terms from index zero
- Recognize recomputation
How it works
- 1
Visit indexes zero through n - 1.
- 2
Call the recursive Fibonacci helper for each index.
- 3
Print returned values on one shared line.
Edge cases
What happens for n = 0?
What happens for n = 0?
No values print; the final newline still runs.
What does n count?
What does n count?
The number of displayed terms, starting at index zero.
What's going on
The outer range supplies indexes zero through n - 1. Each index is passed to fibonacci, whose zero and one base cases stop its recursive calls.
For four terms, the values are 0 1 1 2. The helper uses Python's call stack to wait for smaller results. Calling it separately for every index repeats work, making this a learning example rather than an efficient sequence generator.
What happens for n = 0? No values print; the final newline still runs.
What does n count? The number of displayed terms, starting at index zero.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which indexes print for n = 3?
Pick an answer to check it.
Question 2
What happens for n = 0?
Pick an answer to check it.
Questions people ask
What happens for n = 0?
No values print; the final newline still runs.
What does n count?
The number of displayed terms, starting at index zero.
Which indexes print for n = 3?
0, 1, 2.
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum