Calculates the factorial of a given number in Python

Write a Python Program to Factorial of a given NumberPython Examples-InterviewGIGFactorial in Mathematics:

In mathematics, the factorial of a non-negative integer ‘n’ is the product of all positive integers less than or equal to ‘n’  It is denoted by n! Mathematically,  


For example,5!=5×4×3×2×1=120


Python Program to Calculate Factorial:

Here’s a Python program that calculates the factorial of a given number:

num = int(input("Enter a number: "))
factorial = 1
if num < 0:
    print("Factorial is not defined for negative numbers.")
elif num == 0:
    print("Factorial of 0 is 1.")
    for i in range(1, num + 1):
        factorial *= i
    print("Factorial of", num, "is", factorial)


  1. The program starts by taking an integer input from the user using the `input()` function and converting it into an integer using the `int()` function. This input is stored in the variable `num`.
  2. The variable `factorial` is initialized to 1. This will store the result of the factorial calculation.
  3. The program uses conditional statements (`if`, `elif`, and `else`) to handle different cases:
  • If the input is negative, it prints that factorial is not defined for negative numbers.
  • If the input is 0, it prints that the factorial of 0 is 1.
  • Otherwise, it calculates the factorial using a `for` loop that iterates from 1 to `num + 1`, and at each step, updates the `factorial` by multiplying it with the current value of `i`.
  1. After the loop, the program prints the calculated factorial.


Enter a number: 5
Factorial of 5 is 120

In this example, if the user enters the number 5, the program calculates the factorial of 5 using the formula \( 5! = 5 \times 4 \times 3 \times 2 \times 1 = 120 ) and displays “Factorial of 5 is 120” as the output.

Scroll to Top