math.gamma(x) returns the continuous Gamma function at x as a float, added in Python 3.2.
For any positive integer n, math.gamma(n) equals (n - 1)!, and for non-integers it interpolates smoothly—for example math.gamma(0.5) equals sqrt(math.pi). Zero and negative integers are poles that raise ValueError.
math.gamma() is a function in Python's standard math module: import it with import math and call math.gamma(...), or import the name directly with from math import gamma.
Syntax
Import math and pass a non-pole real number.
python
import math
val = math.gamma(x)
Call
What it does
math.gamma(5.0)
Returns 24.0 (4!).
math.gamma(1.0)
Returns 1.0 (0!).
math.gamma(0)
Raises ValueError: pole at zero.
math.gamma(172)
Raises OverflowError: exceeds float range.
Because gamma(x) grows like factorial and overflows past x ~ 171.6, compute ratios or large values in log space with math.lgamma().
Function signatures
python
math.gamma(x, /)
# added in Python 3.2; returns float Gamma(x)
Parameters
Parameter
Description
x
Required positional real number (int or float), except 0, negative integers, and -inf.
Return Value
Return Value
Description
float
Value of Gamma(x); inf for inf and nan for nan.
Python Examples
Example 1 — Verify math.gamma(n) Equals float(factorial(n - 1))
Compare math.gamma(n) against math.factorial() across integers 1 through 6.
python
import math
for n in range(1, 7):
g = math.gamma(n)
f = float(math.factorial(n - 1))
print(f"n={n}: gamma={g:>5.1f} (n-1)!={f:>5.1f} equal={g == f}")