recursion
In Python, recursion occurs when a function calls itself in order to solve a problem. This approach allows you to break down complex problems into simpler, more manageable sub-problems. Each time a recursive function calls itself, it works on a smaller piece of the problem until it reaches a base case, which is a condition that stops the recursion.
Recursion can be a powerful tool for solving problems involving structures that have a recursive nature, like trees and graphs, or for performing repetitive tasks like calculating factorials.
However, using recursion requires careful management to ensure that the function doesn’t enter an infinite loop. This involves defining a clear base case and ensuring that each recursive call progresses toward this base case.
In Python, recursion is limited by the maximum recursion depth, which is a safety feature to prevent infinite recursion from crashing your programs.
Example
Here’s a quick example of a recursive function that calculates the factorial of a number:
>>> def factorial(n):
... if n == 0:
... return 1
... else:
... return n * factorial(n - 1)
...
>>> print(factorial(5))
120
In this example, the factorial()
function calls itself with a decremented value of n
until it reaches the base case, n == 0
, at which point it returns 1
.
Related Resources
Tutorial
Recursion in Python: An Introduction
In this tutorial, you'll learn about recursion in Python. You'll see what recursion is, how it works in Python, and under what circumstances you should use it. You'll finish by exploring several examples of problems that can be solved both recursively and non-recursively.
For additional information on related topics, take a look at the following resources:
- Thinking Recursively in Python (Tutorial)
- Recursion in Python (Course)
- Thinking Recursively With Python (Course)
By Leodanis Pozo Ramos • Updated July 8, 2025