#570 · Errors and exceptions · Beginner · 35 XP · about 6 min
A function that receives a bad value should stop with an error that tells the caller exactly what was wrong, instead of carrying on with nonsense. Write check_age(age) that returns age when it is a sensible age, and raises an error otherwise:
age is not a whole number (an int), raise a TypeError with the message 'age must be a whole number'. True and False are not ages either, even though Python treats them as 1 and 0.age is a whole number below 0 or above 130, raise a ValueError with the message 'age must be from 0 to 130, got 200', with the real value in place of 200.check_age(15) # returns 15 check_age(200) # raises ValueError: age must be from 0 to 130, got 200 check_age('15') # raises TypeError: age must be a whole number
Raise an error with raise ValueError('your message').
First solves only, ranked by stars and then time.