Sunday, October 5, 2025
HomeLanguagesPython | math.factorial() function

Python | math.factorial() function

In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.factorial() function returns the factorial of desired number.

Syntax: math.factorial(x)

Parameter:
x: This is a numeric expression.
Returns:  factorial of desired number.
Time Complexity: O(n) where n is the input number.
Auxiliary space: O(1)

Code #1: 

Python3




# Python code to demonstrate the working of factorial()
     
# importing "math" for mathematical operations
import math
     
x = 5
     
# returning the factorial
print ("The factorial of 5 is : ", end ="")
print (math.factorial(x))


Output:

The factorial of 5 is : 120

Code #2: 

Python3




# Python code to demonstrate the working of factorial()
 
# importing "math" for mathematical operations
import math
 
x = 5
y = 15
z = 8
 
# returning the factorial
print ("The factorial of 5 is : ", math.factorial(x))
print ("The factorial of 15 is : ", math.factorial(y))
print ("The factorial of 8 is : ", math.factorial(z))


Output:

The factorial of 5 is :  120
The factorial of 15 is :  1307674368000
The factorial of 8 is :  40320

  Code #3: Throws ValueError if x is not integer 

Python3




# Python code to demonstrate the working of factorial()
     
# importing "math" for mathematical operations
import math
     
# when x is not integer
print ("math.factorial(13.7) : ", math.factorial(13.7))


Output:

ValueError: factorial() only accepts integral values
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32337 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6706 POSTS0 COMMENTS
Nicole Veronica
11871 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11935 POSTS0 COMMENTS
Shaida Kate Naidoo
6823 POSTS0 COMMENTS
Ted Musemwa
7089 POSTS0 COMMENTS
Thapelo Manthata
6779 POSTS0 COMMENTS
Umr Jansen
6779 POSTS0 COMMENTS