Home »
Python
math.factorial() method with example in Python
Python math.factorial() method: Here, we are going to learn about the math.factorial() method with example in Python.
By IncludeHelp Last updated : September 19, 2023
Python math.factorial() method
The math.factorial() method is a library method of math module, it is used to find the factorial of a given number, it accepts a positive integer number and returns the factorial of the number.
Note
- The method accepts only integer (positive) value, if the value is either a negative or float – it returns "ValueError".
- If the number is 0 – its factorial will be 1.
Syntax
Syntax of math.factorial() method is:
math.factorial(n)
Parameter(s):
The following are the parameter(s) of math.factorial() method is:
- n – a positive integer number.
Return value
int – it returns factorial of given number n.
Example
Consider the below example with sample input and output:
Input:
a = 6
# function call
print(math.factorial(a))
Output:
720
Python program to demonstrate the example of math.factorial() method
# Python code to demonstrate example of
# math.factorial() method
# importing math module
import math
# numbers
a = 0
b = 1
c = 6
d = 13
# printing factorial
print("factorial of ", a, " is = ", math.factorial(a))
print("factorial of ", b, " is = ", math.factorial(b))
print("factorial of ", c, " is = ", math.factorial(c))
print("factorial of ", d, " is = ", math.factorial(d))
Output
factorial of 0 is = 1
factorial of 1 is = 1
factorial of 6 is = 720
factorial of 13 is = 6227020800
ValueError: factorial() not defined for negative values
If we try to find the factorial of a negative integer value – method will return this error.
# Python code to demonstrate example of
# math.factorial() method
# importing math module
import math
# -ve integer
a = -5
print(math.factorial(a))
Output
Traceback (most recent call last):
File "/home/main.py", line 10, in <module>
print(math.factorial(a))
ValueError: factorial() not defined for negative values
ValueError: factorial() only accepts integral values
If we try to find the factorial of a float value – method will return this error.
# Python code to demonstrate example of
# math.factorial() method
# importing math module
import math
# -ve integer
a = 5.1
print(math.factorial(a))
Output
Traceback (most recent call last):
File "/home/main.py", line 10, in <module>
print(math.factorial(a))
ValueError: factorial() only accepts integral values