Python math.factorial() Method
The Python math.factorial() method is used to calculate the factorial of a non-negative integer. The factorial of a non-negative integer n, denoted as n!, is the product of all positive integers from 1 to n. Mathematically, the factorial of n is calculated as β
n! = n Γ (n-1) Γ (n-2) Γ...Γ 2 Γ 1
In other words, the factorial of n is the product of all positive integers less than or equal to n. By convention, 0! is defined to be 1.
For example β
- 5! = 5 Γ 4 Γ 3 Γ 2 Γ 1
- 4! = 4 Γ 3 Γ 2 Γ 1
- 0! = 1
Syntax
Following is the basic syntax of the Python math.factorial() method β
math.factorial(n)
Parameters
This method accepts a non-negative integer as a parameter for which the factorial is to be calculated.
Return Value
The method returns an integer value representing the factorial of the given non-negative integer n.
Example 1
In the following example, we are calculating the factorial of 5 using the math.factorial() method β
import math
result = math.factorial(5)
print("The result obtained is:",result)
Output
The output obtained is as follows β
The result obtained is: 120
Example 2
Here, we are calculating the factorial of 0 using the math.factorial() method β
import math
result = math.factorial(0)
print("The result obtained is:",result)
Output
Following is the output of the above code β
The result obtained is: 1
Example 3
In this example, we use a variable "n" to store the value "7". We then calculate the factorial of n, denoted as 7! β
import math
n = 7
result = math.factorial(n)
print("The result obtained is:",result)
Output
We get the output as shown below β
The result obtained is: 5040
Example 4
If we pass a non-negative integer to the factorial() method, it raises a ValueError because it only accepts integral values as an argument β
import math
result = math.factorial(5.5)
print("The result obtained is:",result)
Output
The result produced is as shown below β
Traceback (most recent call last):
File "/tmp/main.py", line 2, in <module>
import user_code
File "/tmp/user_code.py", line 2, in <module>
result = math.factorial(5.5)
^^^^^^^^^^^^^^^^^^^
TypeError: 'float' object cannot be interpreted as an integer