Loading lessons...
Recursion
Recursion
Recursion is when a function calls itself. It's a clean way to solve problems that break into smaller copies of themselves.
The classic example: factorial
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
tri_recursion(6)
How it works
tri_recursion(6) calls tri_recursion(5), which calls tri_recursion(4), and so on until k is 0. Then each call returns and adds its value.
A base case is essential
Every recursive function needs a stopping condition:
def countdown(n):
if n <= 0: # base case stops the recursion
print("Done!")
return
print(n)
countdown(n - 1)
Without a base case, you get infinite recursion and a RecursionError.
Recursion depth limit
Python limits how deep recursion can go (about 1000 by default). Very deep recursion errors out.
When recursion shines
- Trees and graphs
- Fractals
- Problems like factorials, Fibonacci, and sorting
TL;DR
- Recursion: a function calls itself.
- Always include a base case that stops it.
- Without one, you hit a RecursionError.
- Great for tree-like or self-similar problems.