`RecursionError` in def factorial(n)

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
        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?

Executing your code gives no error, it works fine.
Please include more of your program so that the code sample actually gives an error.

There are several inputs to factorial() that would make this error happen:

  1. negative number
  2. non-integer number
  3. number too big, around >1000
  4. special numbers that still support math operations

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)
1 Like

Using a loop to calculate the factorial iteratively, which doesn’t rely on recursion, can handle large values like 999 without any issues as well:

def factorial(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result

result = factorial(999)
print("Factorial of 999 is:", result)