Before we start implementing factorial using Python, let us first discuss what factorial of a number implies.
Theoretically, the factorial of a number is defined as the product of all positive integers less than or equal to the number. Certainly, ‘n!’ represents the factorial of an integer ‘n’. As an example, let us look at the factorial of the number 6,
6! = 6 * 5 * 4 * 3 * 2 * 1
The following techniques could be followed to determine the factorial of an integer.
- Using Loop
- Using Recursive function call
- Using predefined function ‘factorial()’ from the math module
Using Loop in Python
The below-mentioned code illustrates how we can calculate the factorial of a given number using for loop in Python programming.
1 2 3 4 5 |
n=9 fact=1 for i in range(2,n+1): fact=fact*i print("The factorial of ",n," is: ",fact) |
Output:
1 2 |
<span style="color: #008000;"><strong>The factorial of 9 is: 362880 </strong></span> |
Using Recursion function call in Python
Similarly, we can also calculate the factorial of a given number using a Recursive function. Let us see how
1 2 3 4 5 6 7 |
n=9 def fact(n): if(n==1 or n==0): return 1 else: return n*fact(n-1) print("The factorial of ",n," is: ",fact(n)) |
Output
1 2 |
<span style="color: #008000;"><strong>The factorial of 9 is: 362880 </strong></span> |
For a clear understanding of functions and recursion, one can refer to
Python Function and Arguments
Python Recursion Function
Using the factorial() method from the math module in Python
The math module provides a simple way to calculate the factorial of any positive integer. Certainly, the module comes with a pre-defined method ‘factorial()’ which takes in the integer as an argument and returns the factorial of the number. Let’s take a look at how we can use the pre-defined method and consequently find the factorial. The code given below depicts how the method ‘factorial()‘ can be used
1 2 3 |
import math n=9 print("The factorial of ",n," is: ",math.factorial(n)) |
Output:
1 2 |
<span style="color: #008000;"><strong>The factorial of 9 is: 362880 </strong></span> |
Furthermore, in the case of all of the above-mentioned techniques, we have used a pre-defined value of the integer ‘n’. Also making ‘n’ a user input is possible. This could be easily achieved by substituting the line ‘n=9’ with:
1 |
n=int(input("Enter the number for calculating factorial")) |
The Python input function is covered in further detail in one of our previous articles.
References:
https://stackoverflow.com/questions/5136447/function-for-factorial-in-python
https://stackoverflow.com/questions/20604185/find-the-best-way-for-factorial-in-python