Python recursion and factorial

A recursive function calls itself with a smaller problem. The base case stops recursion; without it, calls continue until the runtime recursion limit is reached.

Python
def factorial(n):
    if n < 0:
        raise ValueError("n must be nonnegative")
    if n == 0:
        return 1
    return n * factorial(n - 1)

print(factorial(4))
assert factorial(0) == 1
assert factorial(1) == 1
Read the full lesson