Learn the concept
User input, configuration, and API payloads arrive with uncertain types and values. Validation converts that uncertainty into an explicit contract. Check shape first, then convert, then apply domain limits. A field can be syntactically numeric but still outside the allowed range.
Raise a specific exception when a caller supplies invalid input. Keep error messages actionable without echoing sensitive values. Do not catch every possible exception and return a plausible default, because that can conceal programming errors.
Python’s bool is a subclass of int. If a field must be an actual integer rather than true or false, a simple isinstance(value, int) check may be too permissive. Choose validation behavior intentionally. The boundary should reject bad inputs before expensive work begins.
Run and inspect
def read_limit(value):
if type(value) is not int:
raise ValueError("Limit must be an integer")
if not 1 <= value <= 100:
raise ValueError("Limit must be between 1 and 100")
return value
assert read_limit(10) == 10
Your exercise
Test 1, 100, 0, 101, True, "10", and None. Decide whether your application wants to convert text or reject it, and document that choice.
Check your understanding
All invalid cases fail before downstream processing; boundary values succeed.