Contents
Python math.factorial()
math.factorial(x) function returns the factorial of x as an integer.
Syntax
The syntax to call factorial() function is
math.factorial(x)
where
Parameter | Required | Description |
---|---|---|
x | Yes | An integer value. x >= 0. |
Note: Since Python v3.9, factorial() does not accept floats with integral values like 5.0
.
If x is not integral value, then factorial(x) raises ValueError.
Examples
Factorial of integer
In the following program, we shall read an integer from user, and find its factorial.
Python Program
import math
x = int(input('Enter an integer : '))
result = math.factorial(x)
print('Factorial :', result)
Output #1
Enter an integer : 5
Factorial : 120
Output #2
Enter an integer : 0
Factorial : 1
Output #3
Enter an integer : -4
Traceback (most recent call last):
File "/Users/pe/Desktop/Projects/Python/example.py", line 4, in <module>
result = math.factorial(x)
ValueError: factorial() not defined for negative values
Summary
In this Python Examples tutorial, we learned the syntax of, and examples for math.factorial() function.