Let’s understand the different ways to write a Python program to calculate factorial of a number.

What is factorial of a number?

The factorial of a given number (N) is defined as the product obtained by multiplying all the numbers between the given number (N) and 1. For example, the factorial of 5 is the result of the expression 5x4x3x2x1, which is equal to the value 120. Similarly, the factorial of 6 is the result of the expression 6x5x4x3x2x1, which is equal to the value 720. Some important observations.

  • The factorial of number 2 is the value 2 (2! = 2)
  • The factorial of number 1 is the value 1 (1! = 1)
  • The factorial of number 0 is the value 1 (0! = 1)
  • The factorial of negative numbers is not defined
  • Factorial can also be calculated recursively using the definition n!=n*(n-1)!

How to calculate the factorial of a number?

To calculate the factorial of a given number (N), we create a loop which starts with 1 and iterates till the given number N. The factorial value is initialised to 1 before the loop starts. During each iteration, the loop index number is multiplied with the factorial value. As the loop ends, the factorial contains the product of all numbers between 1 and N.

Python Code (to calculate factorial of a number)

#code to calculate factorial 
n = int(input("Enter a number "))
f = 1
i = 1
while i<=n:
    f=f*i
    i=i+1
print("The factorial is", f)

Python Code (to calculate factorial using functions)

The code to calculate factorial of a number can be written using a function. The function takes the number as an arguments and returns the factorial of the number as the result.

#function to calculate factorial 
def factorial(n):
    f=1
    i=1
    while i<=n:
        f=f*i
        i=i+1
    return f

#code to test the above function
n = int(input("Enter a number "))
print("The factorial is", factorial(n))

Python Code (to calculate factorial using recursion)

The function to calculate factorial of a number can be written using recursion, where the function calls itself to calculate the result. Observe that the recursive function does not need a loop to calculate the result, as the recursive function itself behaves like an implicit loop.

#recursive function to calculate factorial 
def factorial(n):
    if n==0:
        return 1
    else:
        return n*factorial(n-1)

#code to test the above function    
n = int(input("Enter a number "))
print("The factorial is", factorial(n))

Similar Programs

Last modified: March 29, 2023

Author