Python: Calculate Factorial

1. Introduction

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It's denoted by n! and is defined as n! = n x (n-1) x (n-2) x ... x 1. For example, 5! = 5 x 4 x 3 x 2 x 1 = 120. In this blog post, we'll develop a Python program that calculates the factorial of a given number.

2. Program Overview

Our program will take an integer input from the user and then compute the factorial using a recursive approach. The base case is that the factorial of 0 is 1.

3. Code Program

def factorial(n):
    """Compute the factorial of n."""
    # Base case: factorial of 0 is 1
    if n == 0:
        return 1
    # Recursive case: n! = n * (n-1)!
    return n * factorial(n-1)

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

# Ensure the number is non-negative
if num < 0:
    print("Please enter a non-negative integer.")
else:
    print(f"The factorial of {num} is {factorial(num)}.")

Output:

For the input 5, the program will output: "The factorial of 5 is 120."

4. Step By Step Explanation

1. The factorial function calculates the factorial using recursion.

2. If the number is 0, it directly returns 1 (base case).

3. For any other number, it returns n multiplied by the factorial of (n-1). This recursion continues until n becomes 0.

4. In the main section, the program prompts the user for input. If the number is negative, it informs the user to enter a non-negative integer.

5. Otherwise, it calls the factorial function and displays the result.

Comments