Overview
- The factorial() function from the math module returns the factorial value for a given integer. The factorial() function raises ValueError when a floating point value or a negative value is passed to it.
- The factorial of a positive integer is given by n! = n*(n-1)(n-2)(n-3)*…*3*2*1.
- The factorial of zero is one.
- The factorial of one is one.
Example 1
# Example Python program that finds the
# factorial for a given number
import math
fl = math.factorial(10)
print("10!=%d"%fl)Output
10!=3628800Example 2
# Example python program that raises a ValueError
# when a negative value is passed to the math.factorial()
# function
import math
# Factorial not defined for negative values
val = math.factorial(-1)
print(val)Output
Traceback (most recent call last):
File "/examples/facto1.py", line 7, in <module>
val = math.factorial(-1)
ValueError: factorial() not defined for negative valuesExample 3
# Example python program that passes floating point value
# to the math.factorial() which raises a ValueError
import math
# Factorial only accepts integer values
val = math.factorial(3.14)
print(val)Output
/examples/facto2.py:6: DeprecationWarning: Using factorial() with floats is deprecated
val = math.factorial(3.14)
Traceback (most recent call last):
File "/Valli/PythonProgs/facto2.py", line 6, in <module>
val = math.factorial(3.14)
ValueError: factorial() only accepts integral values