Python Program to Find Factorial of a Number


The factorial of a number is the multiplication of all the integers from 1 to the number.

Example: Factorial of 5 = 5*4*3*2*1 = 120

Approach 1 – Using for loop

In [1]:
number = int(input("Please Enter Positive Number:"))

if (number == 0):
    print("Factorial of number 0 = 1")
else:
    factorial = 1
    for i in range (number):
        factorial = factorial * (i+1)
    print("Factorial of number", number , "is =", factorial)
Please Enter Positive Number:5
Factorial of number 5 is = 120

In this program, we will ask the user to input the number. Because the factorial of number 0 is always 1, if the number is zero, we will print 0.

Else, we have a for loop to run until range of number. Because it will start from 0 and go until n-1, we will add 1 to i and multiply it by factorial variable. At last, print the factorial.

Approach 2 – Using while loop

In [1]:
number = int(input("Please Enter Positive Number:"))

if (number == 0):
    print("Factorial of number 0 = 1")
else:
    factorial = 1
    counter = number
    while (counter >= 1):
        factorial = factorial * counter
        counter = counter - 1
    print("Factorial of number", number , "is =", factorial)
Please Enter Positive Number:5
Factorial of number 5 is = 120

In this program, we will again ask the user for the input. If the number is 0, print factorial is 1 because the factorial of 0 is always 1.

In the else block, we will use a counter to count from number to 1 and multiply the counter with a factorial variable.

Approach 3 – Using recursion

In [1]:
def factorial(n):
    if n == 1 or n == 0:
        return 1
    else:
        return n * factorial(n-1)

number = int(input("Please enter number:"))
output = factorial(number)
print("Factorial is :", output)
        
Please enter number:5
Factorial is : 120

Here, we use a recursion approach to find the factorial by calling the factorial function again and again.