Factorial Calculation in Python
This document explains how to calculate the factorial of a given number using a Python program. The factorial of a non-negative integer n
is the product of all positive integers less than or equal to n
. It is denoted as n!
and is defined as:
n! = n * (n-1) * (n-2) * ... * 1
Python Program
The following Python program calculates the factorial of a given number using a recursive function:
def factorial(n):
"""
Calculate the factorial of a given number n.
Args:
n (int): The number to calculate the factorial for.
Returns:
int: The factorial of the number n.
Raises:
ValueError: If n is a negative integer.
"""
if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Example usage
if __name__ == "__main__":
try:
number = int(input("Enter a number to calculate its factorial: "))
result = factorial(number)
print(f"The factorial of {number} is {result}.")
except ValueError as e:
print(e)
Explanation
The factorial
function is defined to calculate the factorial of a non-negative integer n
. The function follows these steps:
- If
n
is less than 0, it raises aValueError
because the factorial is not defined for negative numbers. - If
n
is 0 or 1, the function returns 1 because 0! = 1 and 1! = 1 by definition. - For other values of
n
, the function recursively calls itself withn-1
and multiplies the result byn
.
The example usage section prompts the user to enter a number and then calculates and prints its factorial.
How to Run the Program
To run the program, copy the Python code into a file named factorial.py
and execute it using a Python interpreter. For example:
python factorial.py
When prompted, enter a non-negative integer to see the factorial calculation result.