What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
For the factorial of a nonnegative integer in Python, use math.factorial() from the standard library:
import math
n = 5
print(math.factorial(n)) # 120
A factorial multiplies an integer by every positive integer below it: n! = n × (n − 1) × … × 1. By definition, 0! is 1. Python’s documentation describes math.factorial(n) as returning the factorial of the nonnegative integer n (Python 3.14.7 math documentation).
What the factorial function returns
For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. The first values include 0! = 1, 1! = 1, and 5! = 120. The zero case is a mathematical definition, not an error or an empty result (OpenStax, Introduction to Python Programming).
Read a number and handle invalid input
input() returns text, so convert it to an integer before calling math.factorial(). This example reports text that cannot be parsed as an integer and rejects negative integers with a clear message:
#1 Best Overall
import math
try:
n = int(input("Enter a nonnegative integer: "))
if n < 0:
raise ValueError("n must be nonnegative")
print(math.factorial(n))
except ValueError as error:
print(f"Invalid input: {error}")
math.factorial() raises ValueError for negative or non-integral inputs, according to the Python 3.12 math documentation. With the conversion above, inputs such as 3.5 are rejected by int(); a decimal string is not silently treated as a factorial input.
Inputs that need special attention
- Zero:
math.factorial(0)returns1. - Negative integers: They are outside the function’s supported domain; Python raises
ValueError. - Non-integral numbers: They are not factorial inputs for
math.factorial()and raiseValueError. - Integral-valued floats: Do not pass
5.0. Python deprecated accepting such values in 3.9 and stopped accepting them in 3.10; pass the integer5instead (Python math documentation).
Python integers can represent results beyond a fixed machine-width integer range, but factorial results grow quickly, so calculation time and the number of digits in the output increase with the input. No universal practical cutoff follows from the API documentation.
Rank #2
When to write a recursive version
Recursion is useful when the goal is to learn how a problem can be defined in terms of a smaller version of itself. The recurrence is n! = n × (n − 1)!, with 0! and 1! as stopping cases (OpenStax):
def factorial_recursive(n):
if n < 0:
raise ValueError("n must be nonnegative")
if n in (0, 1):
return 1
return n * factorial_recursive(n - 1)
Each call reduces the argument by one until it reaches a base case. Without that stopping case, the function would keep calling itself. Each recursive level also uses a call frame, so for ordinary application code the standard-library function is the simpler choice; use recursion when its teaching value is the point.
Should you use SciPy instead?
For one scalar factorial in ordinary Python, use math.factorial(). SciPy’s scipy.special.factorial is an alternative for scientific workflows, including array inputs, but it has different options and behavior (SciPy reference).
| Function | Typical fit | Result and negative inputs |
|---|---|---|
math.factorial(n) |
Scalar nonnegative integer in standard Python | Exact integer result; negative input raises ValueError. |
scipy.special.factorial(n) |
Scientific or array-oriented calculations | The exact option selects exact integer calculation or a faster floating-point approximation; the documented default for negative values is zero. |
These functions are not interchangeable at the edges: in particular, SciPy’s documented negative-input default does not match the standard library’s exception behavior.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Common confusion: factorial of a number or of its digits?
math.factorial(123) computes 123!, the factorial of the whole integer. It does not compute 1! + 2! + 3! or the factorial of each digit separately. Those are different operations and need a separately specified rule for combining the digit results.
Quick Recap
Best Value
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




