×

python · level 2 · unit 4 · lesson 3

  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

stops a bad value with a message you write.

Python cannot know that a price of -5 makes no sense, but your code can. To a value, check it, and if it is wrong, raise an error yourself: raise ValueError("Price cannot be negative").

Raising stops the function at once, like any other error. Whoever called it can catch it with try and except, or let the program stop with your message.

catches the error and keeps it in a variable called error. Printing it shows the message you wrote.

def set_price(price):
    if price < 0:
        raise ValueError("Price cannot be negative")
    return price
for price in [3.5, -2]:
    try:
        print(f"Price set to {set_price(price)}")
    except ValueError as error:
        print(f"Refused: {error}")

Pick the error that fits: ValueError for a bad value, TypeError for a value of the wrong type.