Input Validation and Error handling with Python

This Python program calculates the factorial of a user-provided number and measures the time taken for the computation. It includes error handling for incorrect input types and values exceeding the maximum allowed integer size. The execution time is displayed in hours, minutes, seconds, and milliseconds.

Code with Original Error:

codeimport math 
from datetime import datetime
import time

num = 0
start = 0
end = 0
# max value is 2147483647
#if __name__ == '__main__':
try:
num = input("Enter a number: ")
except OverflowError:
print("Input cannot exceed 2147483647")
except ValueError:
print("Please enter a non-negative whole number")
except NameError:
print("Must be an integer")
else:
start = datetime.now()
print("The factorial of ", num, " is : ")
print(math.factorial(int(num)))
end = datetime.now()
print(f"Time taken in (hh:mm:ss.ms) is {end - start}")

Key Fixes:

  1. Integer Conversion: The input is immediately converted to an integer using int(input()).
  2. Overflow Check: The input is checked for exceeding the maximum value (2147483647). If so, it raises an OverflowError.
  3. Factorial Calculation: The factorial calculation happens after confirming the input is valid and is an integer.
  4. Timing the Execution: The time taken to compute the factorial is recorded using datetime.now() and the difference is printed.

This code now properly handles user input and ensures that it works for positive integers without unnecessary errors.

Corrected Python Code:

codeimport math
from datetime import datetime

num = 0
start = 0
end = 0

try:
# Taking input and converting it to an integer
num = int(input("Enter a number: "))

# Check if the number is negative
if num < 0:
raise ValueError("Please enter a non-negative whole number")

# Check if the number exceeds maximum allowed value (2147483647)
if num > 2147483647:
raise OverflowError("Input cannot exceed 2147483647")

except OverflowError as oe:
print(oe)

except ValueError as ve:
print(ve)

except NameError:
print("An unexpected error occurred")

else:
start = datetime.now() # Record the start time
print("The factorial of", num, "is:")
print(math.factorial(num)) # Calculate and print the factorial
end = datetime.now() # Record the end time
print(f"Time taken in (hh:mm:ss.ms) is {end - start}")

Explanation:

Understanding Input Validation and Error Handling in Python

Handling user input and preventing errors is a critical aspect of writing robust programs. The code above is designed to compute the factorial of a number entered by the user, while addressing potential errors, such as invalid input types or values.

Common Errors in the Initial Code:

  1. Input Not Being Converted to Integer: The original code takes user input with the input() function but doesn’t immediately convert it to an integer. This can lead to errors when attempting to compute the factorial later. The solution here is to convert the input to an integer right after reading it.
  2. Missing Integer Conversion Before Calculating Factorial: Since input() returns a string, the string needed to be converted to an integer before passing it to math.factorial(). Without this conversion, the program would throw a TypeError.
  3. Improper Use of Exceptions: The original code attempts to handle an OverflowError, ValueError, and NameError, but the use of NameError was unnecessary. The key issue was ensuring that the input is both an integer and a non-negative value, which can be solved with proper validation logic and the use of ValueError for invalid types.
  4. Factorial Calculation Time: The program records the time it takes to compute the factorial using Python’s datetime.now(), and then prints the time taken. This is useful for larger numbers where factorial computation can take more time.

Key Fixes and Enhancements:

  • Input Validation: The program now checks if the input is a non-negative whole number. If not, it raises a ValueError, which is caught and handled appropriately.
  • Overflow Check: Before computing the factorial, the program ensures that the number does not exceed the maximum value of 2147483647, raising an OverflowError if it does.
  • Performance Timing: The program accurately measures and prints the time taken for the factorial calculation, making it useful for analyzing performance when computing factorials of larger numbers.

The End:

In this program demonstrates how to properly handle user input, manage exceptions, and ensure the robustness of Python programs when performing mathematical calculations.

Related blog posts