I’m now working on a Python program with a recursive function, similar to the example on the scaler blog. I’ve discovered a “RecursionError” in my code that I’m trying to understand and resolve.

Here’s a condensed version of my code:

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
result = factorial(5)
print("Factorial of 5 is:", result)

The objective of this code is to use a recursive function to determine the factorial of an integer. When I execute the code, however, I receive the following error message:

RecursionError: maximum recursion depth exceeded in comparison

I’m not sure why this problem is occurring, and I’m having difficulty locating the fault in my code. Could you help tell me what’s generating this problem and how I can fix it?

you’ll always have recursion errors when using recursive functions on large inputs.
A better approach is to use the existing math.factorial. If you expect that your program will compute factorial(n) on non-small n (i.e. n>20), add caching to it:

from math import factorial
from functools import cache
factorial = cache(factorial)