Python Program to Find the Factorial of a Number

In this article you will know how to find a factorial of a number using different techniques.

A factorial of a whole number n is written as n! in mathematics and n1 = n * (n – 1)!

The factorials are used to count the permutations there are n! different ways of arranging n distinct objects into a sequence and the factorial function grows exponentially in computation.

Factorial using for loop

num = int(input("Enter a number: "))
factorial = 1

for i in range(1, num+1):
    factorial *= i

print("The factorial of", num, "is", factorial)

Output

The factorial of 5 is 120

This above program uses a for loop to iterate through the numbers from 1 to num, multiplying each one together to calculate the factorial.
The factorial variable is initialized to 1, since the multiplication of any number by 1 equals the original number.
Then, the for loop goes through each number from 1 to num, multiplying it by the current value of the factorial. Finally, the program prints out the factorial of the input number.

Using recursion to find the factorial

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

num = int(input("Enter a number: "))
print("The factorial of", num, "is", factorial(num))

This program uses a recursive function to calculate the factorial of a number.
The factorial function takes in a number num, and checks if it equals 1. If it does, it returns 1 (since the factorial of 1 is 1). Otherwise, it multiplies num by the result of calling factorial with num-1. This continues recursively until the base case of num=1 is reached. Finally, the program prints out the factorial of the input number.

Output

The factorial of 6 is 720

Leave a Comment