From 739aeea6c065e0c6c2eb89bcaff6a5544762ba22 Mon Sep 17 00:00:00 2001 From: nihals007 Date: Mon, 16 Feb 2026 22:43:35 +0530 Subject: [PATCH] Improve factorial implementation with edge case handling and documentation --- Factorial with Edge Case Handling | 39 +++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/Factorial with Edge Case Handling b/Factorial with Edge Case Handling index 880d9b4..6104483 100644 --- a/Factorial with Edge Case Handling +++ b/Factorial with Edge Case Handling @@ -1,11 +1,30 @@ -try: - n = int(input()) +import math + +def calculate_factorial(n: int) -> int: + """ + Returns the factorial of a non-negative integer. + + Parameters: + n (int): A non-negative integer + + Returns: + int: Factorial of n + + Raises: + ValueError: If n is negative + """ if n < 0: - print("Factorial not defined for negative numbers") - else: - fact = 1 - for i in range(1, n + 1): - fact *= i - print(fact) -except ValueError: - print("Invalid input") + raise ValueError("Factorial not defined for negative numbers") + return math.factorial(n) + + +try: + user_input = input("Enter a non-negative integer: ") + number = int(user_input) + + result = calculate_factorial(number) + print(f"Factorial of {number} is {result}") + +except ValueError as e: + print(f"Error: {e}") +