Python Function to Validate 4-Digit ID Numbers
Validate 4-Digit ID Numbers with Python
This code snippet demonstrates a Python function called isValidID that checks if an input ID number is valid. A valid ID is defined as a 4-digit integer.
class LenError(Exception):
pass
class TypeError(Exception):
pass
def isValidID(IDnum):
try:
if not isinstance(IDnum, int):
raise TypeError
if len(str(IDnum)) != 4:
raise LenError
print('Valid ID number')
return 'Valid ID number'
except TypeError:
return 'The type of your ID is not valid'
except LenError:
return 'The length of your ID is not valid'
# Test cases
assert isValidID('1234') == 'The type of your ID is not valid'
assert isValidID(12340) == 'The length of your ID is not valid'
assert isValidID(1234) == 'Valid ID number'
Explanation:
-
Custom Exceptions: The code defines two custom exception classes,
LenErrorandTypeError, to handle invalid ID lengths and types, respectively. -
Function Logic: The
isValidIDfunction first checks if the inputIDnumis an integer usingisinstance(IDnum, int). If not, it raises aTypeError. -
Length Check: Next, it converts the
IDnumto a string usingstr(IDnum)and checks if its length is 4. If not, it raises aLenError. -
Valid ID: If both checks pass, the function prints 'Valid ID number' and returns the same string.
-
Error Handling: The
try...exceptblock gracefully handles the custom exceptions, returning specific error messages for each case. -
Test Cases: The included assertions verify the function's behavior with different inputs, ensuring it correctly identifies valid and invalid IDs.
原文地址: https://www.cveoy.top/t/topic/ZxU 著作权归作者所有。请勿转载和采集!