# Factorial Program in Python

In the previous article we have seen the logic and code for obtaining the count of the digits in a number, in this article we will see how we can obtain the Factorial of any user-entered number in Python. Before we discuss the Factorial Program in Python, let us revise the concept of Factorial. The factorial of the number n is the product of natural numbers from 1 to n. Denoted by n, pronounced “en-factorial”. The factorial is defined for non-negative integers. The factorial is calculated by the formula: by multiplying all numbers from one to the value of the number itself under the factorial.

Example:

• 3! = 1 * 2 * 3 = 6
• 4! = 1 * 2 * 3 * 4 = 24
• 5! = 1 * 2 * 3 * 4 * 5 = 120
• 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720

### Implementation of Factorial Program in Python

We need a program to accept the user entered number, figure out the factors of that number and then multiply all of them together to obtain the product which makes up their factorial.

```n=int(input("Enter n"))
res=1
for i in range(2, n+1):
res=res+1
print("Factorial is", res)
```
``````Output:
Enter n : 4
Factorial is 2
Factorial is 6
Factorial is 24``````

In the first iteration after the input value is given, the value of 2 is obtained followed by 6 and then the final result of 24 which is the desired output. Let us trace the program manually:

``````Tracing of Program:
res =1
n=4 (Input Result)

After 1st Iteration of loop:
res= 1*2=2

After 2nd Iteration of loop:
res= 2*3=6

After 3rd Iteration of loop:
res= 6 * 4 = 24
``````

Alternatively we could use built-in functions to obtain the factorial through the use of the math library and the factorial( ) function.

```import math
n = int(input("Enter n : "))
res = math.factorial(n)
print("Factorial is", res)
```
``````Output:
Enter n : 6
Factorial is 720``````

Hence we have seen two ways in which the factorial of any given number can be obtained, in the next article we will explore a program to obtain the GCD of two numbers.