math.factorial(n) returns n! (the product 1 * 2 * ... * n) as an exact int for any non-negative integer n, with 0! == 1.
Negative numbers raise ValueError, and floats such as 2.0 raise TypeError since Python 3.10 (Python 3.9 deprecated accepting integral floats). For continuous real inputs, use math.gamma(x + 1).
math.factorial() is a function in Python's standard math module: import it with import math and call math.factorial(...), or import the name directly with from math import factorial.
Syntax
Import math and pass a non-negative integer.
python
import math
n_fact = math.factorial(n)
Call
What it does
math.factorial(0)
Returns 1.
math.factorial(5)
Returns 120.
math.factorial(-1)
Raises ValueError: negative input.
math.factorial(2.0)
Raises TypeError (on Python 3.10+; deprecated in 3.9).
Use math.comb() or math.perm() directly instead of computing huge factorials and dividing them, since they cancel factors before multiplying.
Function signatures
python
math.factorial(n, /)
# returns: exact int n! for int n >= 0
Parameters
Parameter
Description
n
Required positional non-negative integer (int).
Return Value
Return Value
Description
int
Exact factorial of n.
Python Examples
Example 1 — Print Exact Factorials Up to 20! Without Overflow
Watch how rapidly math.factorial() grows while staying an exact Python integer.
python
import math
for n in [0, 1, 5, 10, 20]:
fact = math.factorial(n)
print(f"{n:>2}! = {fact}")
Fractional float rejected. Passing 2.5 raises TypeError; use math.gamma(3.5) for real extensions.
Version note for 2.0. Since Python 3.10, even whole-valued floats like 2.0 raise TypeError.
Frequently Asked Questions
1, matching the empty-product definition in mathematics.
Passing integral floats like 2.0 was deprecated in Python 3.9 and removed in Python 3.10, so factorial() now requires an integer (or object with __index__()).
No. Python integers have arbitrary precision, so factorial(100) computes all 158 digits accurately.
Use math.gamma(x + 1), because gamma(n + 1) equals n! for integers and generalizes to real floats.
No, prefer math.comb(n, k) or math.perm(n, k) (Python 3.8+), which are faster and avoid creating giant intermediate factorials.