Python program to find the factorial of a given number
Understanding Factorials in Python
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 the exclamation mark (n!). For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. Factorials are fundamental in mathematics and computer science, particularly in permutations, combinations, and probability calculations.
This Python program calculates the factorial of a given number using an iterative approach (a simple for loop). It includes input validation to ensure the number is not negative, making it robust and easy to understand for training purposes.
Python Code
# This program calculates the factorial of a given number using an iterative loop.
# Take input from the user and convert it to an integer
num = int(input("Enter a number: "))
# Initialize the factorial variable to 1, as 1 is the multiplicative identity
factorial = 1
# Check if the number is negative, since factorials don't exist for negative numbers
if num < 0:
# Print an error message if the input is negative
print("Factorial does not exist for negative numbers.")
# Check if the number is exactly 0, since 0! is mathematically defined as 1
elif num == 0:
# Output the result immediately for 0
print("The factorial of 0 is 1")
# If the number is positive, proceed to calculate the factorial
else:
# Loop from 1 up to and including the given number
for i in range(1, num + 1):
# Multiply the current factorial value by the loop variable i
factorial = factorial * i
# Print the final calculated factorial value using string formatting
print(f"The factorial of {num} is {factorial}")
Sample Inputs & Outputs
| Scenario | Sample Input | Expected Output |
|---|---|---|
| Standard Positive Case | 5 |
The factorial of 5 is 120 |
| Small Positive Case | 3 |
The factorial of 3 is 6 |
| Edge Case (Zero) | 0 |
The factorial of 0 is 1 |
| Negative Validation Case | -4 |
Factorial does not exist for negative numbers. |
Comments
Post a Comment