How to Find Factorial in Python

The factorial of a number n is defined as the product of all integers from 1 to the number n. For example, the factorial of number 5 is 1*2*3*4*5 = 120. Factorial of number n is represented as n!. For larger values of n, the factorial value is very high. The factorial of zero by convention is defined as 1.

In mathematics, the factorial operation is used in many areas such as mathematical analysis and algebra. For example, n! represents all the permutations of a set of n objects. The notation n! was introduced by french mathematician Christian Kramp in 1808.

1. The following python program uses a simple for loop for computing factorial,

number = int(input("Please enter a number: "))
if number == 0:
    print("0!=", 1)
else:
    factorial = 1
    for i in range(1,number+1): # start from 1
        factorial = factorial*i
    print(number,"!=",factorial)

2. The following python program uses the built-in math module for calculating factorial,

import math
number = int(input("Please enter a number: "))
print(number,"!=",math.factorial(number))

3. The following python program uses a recursive function for calculating factorial. This is possible since n! = n*(n-1)!.

def factorial(n):
    if n <= 1:
        return 1
    else:
        return n * factorial(n - 1)


number = int(input("Please enter a number: "))
print(number, "!=", factorial(number))

Here is the sample output from the above programs,

python3 fact3.py
Please enter a number: 6
6 != 720