def factorial(n):
"""
Calculates the factorial of a non-negative integer.
Args:
n: A non-negative integer.
Returns:
The factorial of n (n!), which is the product of all positive integers
less than or equal to n. Returns 1 if n is 0. Raises a ValueError if n
is negative.
"""
if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")
elif n == 0:
return 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result
# Example Usage:
if __name__ == '__main__':
print(f"Factorial of 0: {factorial(0)}")
print(f"Factorial of 5: {factorial(5)}")
print(f"Factorial of 10: {factorial(10)}")
try:
print(f"Factorial of -1: {factorial(-1)}")
except ValueError as e:
print(f"Error: {e}")
Key improvements and explanations:
Error Handling: The code now explicitly checks for negative input (n < 0) and raises a ValueError with a descriptive message. This is crucial for robustness and adhering to mathematical definitions (factorial is not defined for negative numbers). This makes the function more reliable and prevents unexpected behavior.
Base Case: The code correctly handles the base case n == 0 by returning 1. The factorial of 0 is defined as 1.
Clear and Concise Logic: The else block efficiently calculates the factorial using a for loop and accumulating the product in the result variable.
Docstring: A comprehensive docstring explains what the function does, what arguments it takes, what it returns, and potential errors it might raise. This is essential for readability and maintainability.
if __name__ == '__main__': block: This ensures that the example usage code (the print statements) only runs when the script is executed directly (not when it's imported as a module). This is standard practice in Python.
f-strings: The example usage uses f-strings for clearer and more readable output.
Explicit result Variable: Using result makes the code's intention clearer compared to modifying n directly in the loop.
Testability: The code is now easily testable. You can write unit tests to verify that it correctly calculates factorials for various inputs and handles errors properly.
Efficiency: For larger values of n, a recursive implementation can be less efficient than an iterative one due to function call overhead. This iterative implementation is generally more efficient for most practical uses.
How to run the code:
Save: Save the code as a Python file (e.g., factorial.py).
Run: Open a terminal or command prompt, navigate to the directory where you saved the file, and run the script using python factorial.py.
The output will be:
code
Factorial of 0: 1
Factorial of 5: 120
Factorial of 10: 3628800
Error: Factorial is not defined for negative numbers.
This improved version is significantly more robust, readable, and adheres to best practices for Python code. It handles edge cases correctly and provides clear error messages.