Write a function that validates a person's age.
validate_age(age)
If age is negative or greater than 130, raise a ValueError with the message "age must be between 0 and 130". Otherwise, return age unchanged.
validate_age(30) // → 30
validate_age(0) // → 0
validate_age(-1) // raises ValueError("age must be between 0 and 130")
validate_age(200) // raises ValueError("age must be between 0 and 130")
This is the other half of exception handling: instead of reacting to an exception Python raises for you, you decide when your own code's input is invalid and raise on purpose.
The rule is simple — age is only valid between 0 and 130 inclusive. Anything outside that range means the caller passed bad data, and it's validate_age's job to say so clearly rather than silently accepting garbage or returning some sentinel value that might get used by mistake.
raise ValueError("age must be between 0 and 130") does two things: it stops execution immediately (nothing after the raise runs), and it hands the caller a message explaining exactly what went wrong, via str(e) if they catch it.
Why ValueError specifically? Because the type of age is fine — it's an int, as expected — it's the value that's unacceptable. That's precisely what ValueError means, as opposed to TypeError (wrong type entirely).
def validate_age(age):
if age < 0 or age > 130:
raise ValueError("age must be between 0 and 130")
return age
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.