Everything that is done with recursion can be done with a loop, and vice versa. So why use it? And, above all, when not to?
The same function in two ways
# With a loop
def sum_loop(n):
total = 0
for i in range(1, n + 1):
total += i
return total
# Recursive
def sum_rec(n):
if n == 0:
return 0
return n + sum_rec(n - 1)
print(sum_loop(100), sum_rec(100)) # 5050 5050
When recursion is a good fit
- When the problem is recursive by nature: tree-shaped structures (folders inside folders), nested expressions, divide-and-conquer algorithms.
- When the recursive code is much shorter and clearer than the loop equivalent.
- When the depth is small and known.
When a loop is a better fit
- When the problem is a simple repetition (adding, counting, going through).
- When there may be many repetitions: Python is not efficient with hundreds of nested calls.
- When performance matters.
The recursion limit
Python allows about 1000 stacked calls. Beyond that, a RecursionError occurs:
import sys
print(sys.getrecursionlimit()) # 1000
print(sum_rec(5000)) # RecursionError: maximum recursion depth exceeded
With the loop, sum_loop(5000) works with no problem.
The hidden cost of Fibonacci
The recursive version of Fibonacci repeats the same calculations over and over. To calculate fibonacci(5) it already makes 9 calls; the number of calls grows very fast:
| n | fibonacci(n) | Calls made |
|---|---|---|
| 5 | 5 | 9 |
| 10 | 55 | 109 |
| 20 | 6765 | 13,529 |
| 30 | 832,040 | 1,664,079 |
With n = 40 it would already take minutes. There are two ways to fix it.
1. With a loop, which keeps only the last two values:
def fibonacci_loop(n):
a, b = 1, 1
for _ in range(n - 2):
a, b = b, a + b
return b
print(fibonacci_loop(50)) # 12586269025, instantly
2. Storing the results already calculated (memoization). Python does it for you with lru_cache:
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n <= 2:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(50)) # 12586269025, instantly
For the exercises in this lesson, the values of n are small and the simple recursive version is enough.
Common mistakes
- Missing base case or never reached (for example, calling with
n + 1when you expect to get to 0):RecursionError. - The problem does not shrink: calling with the same value again.
- Forgetting the return in the recursive case: the function returns
None. - Incomplete base cases:
fibonaccineeds two (n == 1andn == 2); with only one,fibonacci(2)would callfibonacci(0)and leave the expected range. - Strings or lists that never become empty: if the base case is
len(text) == 0but you reduce by 2 and the input may have one character, you never reach 0. Check the base case with every size.
def bad(n):
if n == 0:
return 0
n + bad(n - 1) # missing return → returns None
print(bad(1)) # None (with a larger n, TypeError when adding None)
Debugging a recursive function
Add a print at the start with the argument to see how the problem shrinks:
def sum_to(n):
print("call with", n)
if n == 0:
return 0
return n + sum_to(n - 1)