PythonMastery

Factorial using recursion in Python

A recursive factorial function: the base case, the recursive call, and why very large inputs raise a RecursionError in Python.

A recursive function is a function that calls itself. Factorial fits this well, because n! = n × (n - 1)!. For example, 5! = 5 × 4!.

The program

python
def factorial(n):
    if n < 0:
        raise ValueError("factorial is not defined for negative numbers")
    if n <= 1:
        return 1
    return n * factorial(n - 1)


for n in [0, 1, 5, 10]:
    print(f"{n}! = {factorial(n)}")
output
0! = 1
1! = 1
5! = 120
10! = 3628800

How it works

The recursion limit

Every call that is still waiting uses memory. To protect the program, Python stops after about 1,000 nested calls and raises a RecursionError:

python
import sys


def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)


print("Limit:", sys.getrecursionlimit())

try:
    factorial(5000)
except RecursionError:
    print("factorial(5000) failed: too many nested calls")
output
Limit: 1000
factorial(5000) failed: too many nested calls

For large numbers, use the loop version or math.factorial(). Both work for 5000 without any problem. Recursion is still worth learning, because some problems (trees, folders inside folders) are much easier to write with it.

Learn the idea: Functions & Scoping