Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

IntermediatePhase 3 - Level 1: Basic RecursionExample 9 of 10
fibonacci-series-recursively.py
1def fibonacci(n):
2 if n == 0:
3 return 0
4 if n == 1:
5 return 1
6 return fibonacci(n - 1) + fibonacci(n - 2)
7
8# Print series
9n = 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. 1

    Visit indexes zero through n - 1.

  2. 2

    Call the recursive Fibonacci helper for each index.

  3. 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.