Python Program to Find the Factorial of a Number

1. Introduction

The factorial of a number is a fundamental concept in mathematics and computer science, defined as the product of all positive integers less than or equal to that number. For example, the factorial of 5 (denoted as 5!) is 5 x 4 x 3 x 2 x 1 = 120. Factorials are used in various areas, including permutations and combinations, algorithm design, and in the calculation of probabilities. Python provides a straightforward way to calculate the factorial of a number, which can be particularly useful for educational purposes, mathematical computations, and algorithmic challenges. This blog post will guide you through creating a Python program to calculate the factorial of a given number.

2. Program Steps

1. Prompt the user to enter a non-negative integer.

2. Check if the entered number is less than 0; if so, print an error message.

3. If the number is 0 or 1, its factorial is 1.

4. For numbers greater than 1, calculate the factorial by multiplying all integers from 2 to the number itself.

5. Display the factorial of the number.

3. Code Program

# Step 1: Prompt the user for the number
num = int(input("Enter a number: "))

# Function to calculate factorial
def factorial(n):
    # Step 2: Base case for factorial(0) and factorial(1)
    if n == 0 or n == 1:
        return 1
    # Step 3: Recursive case for n > 1
    else:
        return n * factorial(n - 1)

# Step 4: Check if the user input is negative
if num < 0:
    print("Sorry, factorial does not exist for negative numbers.")
else:
    # Calculate the factorial of the number
    print(f"The factorial of {num} is {factorial(num)}")

Output:

Enter a number: 5
The factorial of 5 is 120

Explanation:

1. The program begins by asking the user to input a non-negative integer, which will be used to calculate its factorial.

2. A function named factorial is defined to calculate the factorial of the number. It uses a simple recursive approach where the factorial of n is n multiplied by the factorial of n - 1. The recursion stops when it reaches base cases where the factorial of 0 or 1 is defined as 1.

3. Before calling the factorial function, the program checks if the user has entered a negative number. Since factorials of negative numbers are not defined, it prints an error message in such cases.

4. If the number is non-negative, the program calculates its factorial by calling the factorial function and displays the result.

5. This approach demonstrates the use of recursion to solve a problem efficiently, providing a clear example of how to calculate factorials in Python.


Comments