Python Program for Factorial of a Number

1. Introduction

The factorial of a number is a fundamental concept in mathematics and computer science, particularly in combinatorics and discrete mathematics. The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, the factorial of 5 (5!) is 5 * 4 * 3 * 2 * 1 = 120. The value of 0! is 1, according to the convention for an empty product. This blog post will guide you through writing a Python program to calculate the factorial of a given number using a simple iterative approach.

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 to enter a number
num = int(input("Enter a number: "))

# Step 2: Check if the number is negative
if num < 0:
    print("Sorry, factorial does not exist for negative numbers")
else:
    # Step 3: Initialize the factorial value to 1
    factorial = 1
    # Step 4: Calculate the factorial for numbers greater than 1
    for i in range(1, num + 1):
        factorial = factorial * i
    # Step 5: Display the result
    print(f"The factorial of {num} is {factorial}")

Output:

Enter a number: 5
The factorial of 5 is 120

Explanation:

1. The program starts by asking the user to input a number. This number is stored as an integer.

2. It then checks if the number is negative. Factorials of negative numbers are not defined, so it prints an error message in such cases.

3. The factorial of 0 and 1 is 1 by definition. Therefore, if the number is 0 or 1, the program sets the factorial to 1.

4. For numbers greater than 1, the program calculates the factorial by iterating through all integers from 1 to the number itself, multiplying each integer by the running total to calculate the factorial.

5. Finally, the program prints the factorial of the number, demonstrating how to calculate factorials using a straightforward iterative approach.


Comments