math.factorial() in Python with examples

We know that Python is a high-level programming language that provides multiple modules to make coding easy and efficient. One of such modules is ‘math’, which provides numerous functions such as factorial(), sqrt(), ceil(), fabs() etc. In this tutorial, we will be learning how to use the factorial() function defined in the math module of Python with the help of some examples. For this tutorial, we will be using python3, so make sure you have python3 installed in your system.

Importing the math module in Python

1.  This is step 1 of the process. We need to import the math module into our code. For this, type:

(Example A)

import math

We can also import math module as follows:

(Example B)

from math import *

Passing the value to factorial() function

2.  In this step, we pass the desired values to our factorial() function. For instance, we we want to calculate the factorial of 7, the complete code will be as follows:

import math
print(math.factorial(7))

Or if we have used example B, we can simply call the factorial() function as follows:

from math import *
print(factorial(7))

In both the examples, output will be:

5040

Example to take a number as an input and print its factorial

from math import *
a = int(input("Enter the number: "))
print(factorial(a))

Output:

Enter the number: 4
24

The above code asks user to enter a number and calculates its factorial. However, the factorial function does not works with decimal values. For example, if we re-run the above code and provide a decimal value as an input:

Output:

Enter the number: 5.6
Traceback (most recent call last):
File "a.py", line 2, in <module>
a = int(input("Enter the number: ")) 
ValueError: invalid literal for int() with base 10: '5.6'
>>>

We can see, that the code raises an error. Hence, factorial() is strictly for integral values greater than or equal to zero.

NOTE: The factorial of zero is 1.

Also read: Math module of Python

Leave a Reply

Your email address will not be published. Required fields are marked *