×

python · level 3 · unit 7 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

data once, at the door, then trust it inside.

Anything from outside your program can be wrong: typed answers, files, form fields, API replies. Validate it the moment it arrives, at the door, and turn it into clean values. Code further in can then trust what it receives.

Write each check as a : an if at the top that raises an error at once. Raise a , a class of your own like BadAge, so callers can catch exactly your problem and nothing else. Its body is pass, which means nothing more to add.

class BadAge(ValueError):
    pass

def parse_age(text):
    text = text.strip()
    if not text.isdigit() or int(text) > 130:
        raise BadAge(f"not a real age: {text}")
    return int(text)

for answer in [" 42 ", "forty", "-3", "200"]:
    try:
        print("age", parse_age(answer))
    except BadAge as problem:
        print("rejected,", problem)

Inheriting from ValueError means older code that catches ValueError still catches your error too.