python · level 2 · unit 4 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A table for nobody. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
def book_table(people):
if people < 1:
raise ValueError("Book for at least 1 person")
print(f"Table for {people} booked")
book_table(4)
book_table(0)
print("All done")
your turn
Your turn. Guard the age box.
On line 3, type the word that causes an error on purpose, then the kind of error that means a bad value. We will type 150.
fix it
The bank's message has gone missing. Can you fix it?
- Read the last line of the error. Which name does Python not know?
erroris never created. Theexceptline has to give the caught error a name.- Change line 7 to except ValueError as error: and run.
nailed it
you set your own rules. :D
- Validate values and
raisean error when they make no sense. - Write a clear message:
raise ValueError("..."). except ValueError as error:lets you show that message.
new words in your collection
- raise
- validate
- as
This lesson isn’t saved. A free account remembers every lesson you finish.