RecursionError
is a built-in exception that occurs when the maximum recursion depth is exceeded. Recursion is a programming technique where a function calls itself to solve a problem.
Without a proper base case that stops the recursive calls, recursion can lead to potentially infinite loops, consuming memory with each call. To prevent this, Python sets a limit on the recursion depth. Exceeding this limit triggers a RecursionError
.
RecursionError
Occurs When
A RecursionError
appears when a function calls itself directly or indirectly often enough to reach Python’s recursion limit.
RecursionError
Can Be Used When
Typically, you won’t raise RecursionError
yourself. When Python raises a RecursionError
, you can use it as a sign that your recursive code logic is buggy.
RecursionError
Example
An example of when the exception appears:
As this recursive function doesn’t have a proper base case that ends the call cycle, it will keep calling itself until Python eventually raises a RecursionError
.
RecursionError
How to Fix It
Here’s another buggy piece of code that raises a RecursionError
:
To fix it, ensure your function has a base case that terminates the recursion:
The highlighted lines add a base case that terminates the recursion when the value of n
goes down to zero.
By default, Python has a recursion depth limit of 1000 calls:
You can change this limit using the sys.setrecursionlimit()
function.
Tutorial
Recursion in Python: An IntroductionIn 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:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4