Factorial Function - Python Math Module

Overview:

  • The factorial() function from the math module returns the factorial value for a given integer.
  • The function raises ValueError when a floating point value or a negative value is passed.

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!=3628800

Example 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 values

Example 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

 


Copyright 2022 © pythontic.com