Python Factorial Examples

The factorial of a number n is the product of every integer from 1 to n. factorial(5) = 5 * 4 * 3 * 2 * 1 = 120. The operation shows up in probability, permutations, and series expansions. Python makes it trivial to compute. This guide covers every way to do it.

By the end you will know how to use the built-in math module, how to write an iterative version, and how recursion gives you the cleanest implementation of all.

Using math.factorial()

Python ships with a factorial function in the standard library. Import math and call it directly.

import math

result = math.factorial(5)
print(result)  # 120

One detail worth knowing: math.factorial(0) returns 1 by definition. This is a mathematical convention that matters when factorial shows up in combinations and permutations formulas.

print(math.factorial(0))  # 1
print(math.factorial(1))  # 1

The math module throws a ValueError if you pass a negative integer or a non-integer. For production code that needs to handle invalid input gracefully, you have to add your own validation layer on top.

def safe_factorial(n):
    if not isinstance(n, int):
        raise TypeError("n must be an integer")
    if n < 0:
        raise ValueError("n must be non-negative")
    return math.factorial(n)

print(safe_factorial(5))   # 120
print(safe_factorial(-1))  # ValueError

Iterative Implementation

The iterative approach multiplies each number from 1 to n into a running product. This is the version most people writes first and it works exactly as you would expect.

def factorial(n):
    if n < 0:
        raise ValueError("n must be non-negative")
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result

print(factorial(5))   # 120
print(factorial(7))   # 5040

The loop runs n times, so the time complexity is O(n). Each multiplication is constant time. Space usage is O(1).

Recursive Implementation

The recursive version is shorter and reveals the mathematical structure more clearly. factorial(n) = n * factorial(n-1), and factorial(0) = 1 as the base case.

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

print(factorial(5))   # 120
print(factorial(7))   # 5040

Every recursive call adds a frame to the call stack. For large n this can trigger a RecursionError in Python. The iterative version does not have this problem.

Using reduce()

Functional programming fans can use reduce from functools to accumulate the product without an explicit loop.

from functools import reduce

def factorial(n):
    if n < 0:
        raise ValueError("n must be non-negative")
    return reduce(lambda a, b: a * b, range(1, n + 1), 1)

print(factorial(5))   # 120
print(factorial(0))   # 1

The third argument to reduce is the initial value (1), which handles the factorial(0) case correctly.

Handling Large Numbers

Python handles arbitrarily large integers natively. factorial(100) produces a 158-digit number without any special handling.

import math
print(math.factorial(100))

The result grows extremely fast. factorial(208) is approximately 10^374. Beyond that, Python automatically switches to arbitrary precision integers.

FAQ

What is factorial(0)?

factorial(0) is defined as 1. This convention exists because there is exactly one way to arrange zero objects (by doing nothing). It also makes the recursive definition work cleanly since factorial(1) = 1 * factorial(0) = 1.

Can Python handle very large factorials?

Yes. Python integers have arbitrary precision. math.factorial(10000) computes and stores a 35660-digit number without any special code. The only constraint is memory.

Which implementation should I use?

Use math.factorial in production code. It is implemented in C and optimized. Write your own version only when learning or when you need custom behavior.

Why does factorial crash on negative numbers?

Factorial is mathematically undefined for negative integers. Python math.factorial raises ValueError for negative input.

Ninad
Ninad

A Python and PHP developer turned writer out of passion. Over the last 6+ years, he has written for brands including DigitalOcean, DreamHost, Hostinger, and many others. When not working, you'll find him tinkering with open-source projects, vibe coding, or on a mountain trail, completely disconnected from tech.

Articles: 132