The factorial() function - Python math module

The factorial() function returns the factorial of a given integer. The function does not allow the input to be negative value or a floating point value.

Math Updated 20 Aug 2021 1 min read

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

python
# Example Python program that finds the

            # factorial for a given number

            import math

fl = math.factorial(10)

            print("10!=%d"%fl)

Output

Output
10!=3628800

Example 2

python
# 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

Output
Traceback (most recent call last):

  File "/examples/facto1.py", line 7, in <module>

    val = math.factorial(-1)

ValueError: factorial() not defined for negative values

Example 3

python
# 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

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