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:

  1. Custom Exceptions: The code defines two custom exception classes, LenError and TypeError, to handle invalid ID lengths and types, respectively.

  2. Function Logic: The isValidID function first checks if the input IDnum is an integer using isinstance(IDnum, int). If not, it raises a TypeError.

  3. Length Check: Next, it converts the IDnum to a string using str(IDnum) and checks if its length is 4. If not, it raises a LenError.

  4. Valid ID: If both checks pass, the function prints 'Valid ID number' and returns the same string.

  5. Error Handling: The try...except block gracefully handles the custom exceptions, returning specific error messages for each case.

  6. Test Cases: The included assertions verify the function's behavior with different inputs, ensuring it correctly identifies valid and invalid IDs.

Python Function to Validate 4-Digit ID Numbers

原文地址: https://www.cveoy.top/t/topic/ZxU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录