factorial() in Python

Last Updated : 18 Dec, 2025

The factorial of a number n (written as n!) is the product of all positive integers from 1 to n.

For example:

5! = 1 * 2 * 3 * 4 * 5 = 120.

Python provides a function math.factorial() that computes factorial without writing the entire loop manually.

Syntax

math.factorial(x)

Parameters: x -> number whose factorial you want (must be a non-negative integer).

Examples of math.factorial()

Example 1: This example uses math.factorial() to compute factorial directly using Python’s inbuilt function.

Python
import math
print(math.factorial(6))

Output
720

Example 2: This example shows what happens when you pass a negative number to math.factorial(). Python raises a ValueError.

Python
import math
print(math.factorial(-3))

Output

ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
ValueError: factorial() not defined for negative values

Explanation: math.factorial(-3) triggers an error because factorial for negative numbers does not exist.

Example 3: This example demonstrates that factorial only works with integers. Passing a float raises a ValueError.

Python
import math
print(math.factorial(4.7))

Output

ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
TypeError: 'float' object cannot be interpreted as an integer

Explanation: math.factorial(4.7) raises error because fractional factorial values are not supported.

Comment