To get a factorial in Python, call math.factorial(n) from the standard library: math.factorial(5) returns 120. If you need to write it yourself, a for loop that multiplies the numbers from 2 to n gives the same exact result.
import math
print(math.factorial(5)) # 120
The factorial of a nonnegative integer n, written n!, is the product of all whole numbers from 1 up to n. So 5! = 5 × 4 × 3 × 2 × 1 = 120. Below are four ways to compute it, what each does with bad input, and how large the results get.
Factorial in Python with math.factorial
The standard-library function is the right default. The Python documentation describes it as returning n factorial as an integer, and it raises ValueError if n is negative. It is implemented in C, so you don't need to write or test any logic yourself.
import math
print(math.factorial(0)) # 1
print(math.factorial(1)) # 1
print(math.factorial(10)) # 3628800
print(math.factorial(20)) # 2432902008176640000
Those values are easy to check by hand or with a calculator: 10! = 3,628,800 and 20! = 2,432,902,008,176,640,000. Because Python integers can grow as large as memory allows, the result is always exact. There is no overflow at 20! or 21! as there is with a 64-bit integer type in languages like C or Java.
Factorial with a for loop
A loop is the simplest version to write when you are learning, or when an exercise forbids the math module.
def factorial(n: int) -> int:
if n < 0:
raise ValueError("factorial is not defined for negative numbers")
result = 1
for number in range(2, n + 1):
result *= number
return result
print(factorial(5)) # 120
print(factorial(0)) # 1
Two details make this correct. First, result starts at 1, not 0, because starting at zero would make every product zero. Second, range(2, n + 1) stops before its end value, so the + 1 is what includes n itself. Multiplying by 1 changes nothing, which is why the loop can start at 2. For n = 0 and n = 1 the range is empty, the loop body never runs, and the function returns 1. That matches the definition 0! = 1 with no special case. If range boundaries are still confusing, see Python range() function examples.
Factorial with recursion
The definition n! = n × (n - 1)! translates directly into a recursive function. It is a common teaching example.
def factorial(n: int) -> int:
if n < 0:
raise ValueError("factorial is not defined for negative numbers")
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
The line if n <= 1: return 1 is the base case. Without it the function would call itself forever. Every call adds a frame to the call stack, and Python limits the depth of that stack. The sys documentation says the recursion limit exists to stop infinite recursion from overflowing the C stack and crashing the interpreter, and you can read it with sys.getrecursionlimit(). A recursive factorial of a large n therefore fails with RecursionError long before the loop version or math.factorial has any trouble. The error and its causes are covered in RecursionError: maximum recursion depth exceeded. For production code, prefer the loop or the library function.
Factorial with math.prod
Since a factorial is a product, math.prod can compute it from a range. The documentation gives the signature as prod(iterable, *, start=1), and notes it was added in Python 3.8.
import math
n = 6
print(math.prod(range(1, n + 1))) # 720
When the iterable is empty, math.prod returns the start value, which defaults to 1. That means math.prod(range(1, 1)) is 1, so zero works here too. Still, if the only goal is a factorial, math.factorial says what you mean more clearly.
Which method to use
| Method | Best for | Negative input | Watch out for |
|---|---|---|---|
math.factorial(n) | Real code | Raises ValueError | Floats are not accepted in current Python |
for loop | Learning, exercises | Only if you add a check | Start the result at 1, and end the range at n + 1 |
| Recursion | Teaching the idea | Only if you add a check | Hits the recursion limit for large n |
math.prod(range(1, n + 1)) | When you are already using prod | Returns 1 for n = 0, and for negative n the empty range also gives 1 | Silently wrong for negative n unless you validate |
The last row is the one that catches people. math.prod(range(1, -3 + 1)) iterates over an empty range and returns 1, where math.factorial(-3) correctly refuses. If the number comes from outside your program, validate it first.
What happens with negative numbers and floats
Factorial is only defined for nonnegative integers, and math.factorial enforces that.
import math
math.factorial(-1)
Example output:
ValueError: factorial() not defined for negative values
The exact wording of the message can differ between Python versions, so catch ValueError rather than matching the text. Floats are a separate case. The documentation for Python 3.9 marks accepting integral floats such as 5.0 as deprecated, and the current documentation says they are no longer accepted as of 3.10. If you have a whole number stored as a float, convert it explicitly:
import math
value = 5.0
print(math.factorial(int(value))) # 120
Only do this when you know the float is whole. int(5.7) silently drops the fraction and gives 5. For a factorial-like function over non-integers there is math.gamma, which the documentation describes as the Gamma function. Its relationship to factorials is gamma(n + 1) == n! for positive integers, but it returns a float and loses exactness for large values, so it is not a replacement for math.factorial.
How big do factorials get?
Very quickly. 20! already has 19 digits, and 25! is 15511210043330985984000000. math.factorial(100) has 158 digits, and Python returns every one of them correctly. You can count the digits yourself:
import math
print(len(str(math.factorial(100)))) # 158
There is one limit to know about. Python 3.11 added a cap on converting very large integers to decimal strings, and the default is exposed as sys.int_info.default_max_str_digits. Printing a factorial with more digits than the cap raises ValueError, even though the integer itself was computed fine. You can read the current setting with sys.get_int_max_str_digits() and change it with sys.set_int_max_str_digits(). You are unlikely to meet this with ordinary exercise values, but it matters if you print something like math.factorial(5000).
Related functions: permutations and combinations
Many factorial questions are really counting questions. The standard library covers the two most common ones, and both are exact integers.
math.perm(n, k)counts ordered selections ofkitems fromn, which isn! / (n - k)!. Ifkis omitted it defaults tonand returnsn!.math.comb(n, k)counts unordered selections, which isn! / (k! * (n - k)!).
import math
print(math.perm(5, 2)) # 20
print(math.comb(5, 2)) # 10
Both return 0 when k is greater than n, and both raise ValueError for negative arguments. Use them instead of dividing two factorials yourself. Dividing with / produces a float and can lose precision for large values, and computing the huge intermediate factorials is wasted work.
Taking input from a user safely
A small wrapper handles the failure cases when the number is typed in.
import math
text = input("Enter a nonnegative integer: ")
try:
number = int(text)
print(math.factorial(number))
except ValueError:
print("Please enter a whole number that is 0 or greater.")
Both int("abc") and math.factorial(-4) raise ValueError, so one handler covers a typo and a negative number. Be aware that int("5.0") also fails, because the string is not a plain integer literal.
Frequently asked questions
- What is the factorial of 0 in Python?
- math.factorial(0) returns 1. By definition 0! is 1, because the product of no numbers is 1, and math.factorial follows that definition. A loop that starts its result at 1 and multiplies over range(2, n + 1) gives the same answer without a special case.
- What happens if I pass a negative number to math.factorial?
- It raises ValueError. The Python documentation says math.factorial raises ValueError if n is negative. Factorial is only defined for nonnegative integers, so check the input yourself if it comes from a user and show a clear message instead of a traceback.
- Can I take the factorial of a float like 5.0?
- Not in current Python. Accepting floats with integral values was deprecated in Python 3.9 and the documentation states they are no longer accepted from Python 3.10. Convert with int(5.0) first if you know the value is whole. For non-integer values the gamma function, math.gamma, is the usual extension.
- Is there a limit on how large a factorial Python can compute?
- Python integers have no fixed size limit, so math.factorial returns an exact result as long as you have the memory and the time. Printing a huge result as a decimal string can hit the integer-to-string digit limit that was added in Python 3.11, which you can inspect with sys.get_int_max_str_digits().