Write a Python Program to Find the Factorial of a Number

The factorial of a number is the product of all positive integers from 1 to that number. It is denoted by n! and is commonly used in combinatorics, probability, and algebra.

For example:

  • 5! = 5 ร— 4 ร— 3 ร— 2 ร— 1 = 120
  • 4! = 4 ร— 3 ร— 2 ร— 1 = 24

In this tutorial, we will write a Python program to find the factorial of a number using different methods.

What is Factorial?

The factorial of n (n!) is calculated as:

\[n! = n \times (n โ€“ 1) \times (n โ€“ 2) \times \dots \times 1\]

By definition:

โœ” 0! = 1 (Factorial of zero is always 1)

Method 1: Using a Loop (Iterative Approach)

# Taking user input
num = int(input("Enter a number: "))

factorial = 1

# Factorial is only defined for non-negative integers
if num < 0:
    print("Factorial is not defined for negative numbers.")
elif num == 0:
    print("The factorial of 0 is 1")
else:
    for i in range(1, num + 1):
        factorial *= i
    print(f"The factorial of {num} is {factorial}")

Output 1: Positive Number

Enter a number: 5
The factorial of 5 is 120

Output 2: Negative Number

Enter a number: -7
Factorial is not defined for negative numbers.

Output 3: Zero (Edge Case)

Enter a number: 0
The factorial of 0 is 1

Method 2: Using Recursion

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

# Taking user input
num = int(input("Enter a number: "))

if num < 0:
    print("Factorial is not defined for negative numbers.")
else:
    print(f"The factorial of {num} is {factorial(num)}")

How Recursion Works?

Recursion is a technique where a function calls itself. The recursive function stops when n = 0.

For example, calculating factorial(5) works as:

5!=5ร—4!=5ร—4ร—3!=5ร—4ร—3ร—2!=5ร—4ร—3ร—2ร—1!=120

Method 3: Using the math Module

import math

# Taking user input
num = int(input("Enter a number: "))

if num < 0:
    print("Factorial is not defined for negative numbers.")
else:
    print(f"The factorial of {num} is {math.factorial(num)}")

โœ” This is the simplest method as Pythonโ€™s math.factorial() handles all the logic internally.

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! Iโ€™m Subhankar Rakshit, the brains behind PySeek. Iโ€™m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles:ย 198