Python Python Basics All Together Now Handle Exceptions

Danny Rosenbaum
Danny Rosenbaum
723 Points

The final code gives an invalid literal error message when using a spelled out number. How do I prevent that message?

I am spelling out a number i.e. "Four" instead of "4" and I am getting an error message that says invalid literal.

Lucas Taylor
Lucas Taylor
125 Points

Can you please post an example or piece of the code?

Danny Rosenbaum
Danny Rosenbaum
723 Points

The code looks like this:

while tickets_remaining >= 1:
print("There are {} tickets remaining.".format(tickets_remaining))
name = input("What is your name? ") tickets_requested = input("Hello, {}! How many tickets would you like to order for the show? ".format(name)) #Expect Value Error try: tickets_requested = int(tickets_requested) if tickets_requested > tickets_remaining: raise ValueError("I'm sorry, we only have {} tickets remaining.".format(tickets_remaining)) except ValueError as err: print("Oh no! We ran into an issue. {} Try again!".format(err))

The error looks like this:

treehouse:~/workspace$ python masterticket.py

There are 100 tickets remaining.
What is your name? dan
Hello, dan! How many tickets would you like to order for the show? four
Oh no! We ran into an issue. invalid literal for int() with base 10: 'four' Try again!
There are 100 tickets remaining.
What is your name?

Danny Rosenbaum
Danny Rosenbaum
723 Points

Sorry the indenting didn't copy over as expected.

1 Answer

Steven Parker
Steven Parker
186,980 Points

The "int(tickets_requested)" function converts a string made of digits (like "4") into a number (4). But it does not recognize words and that causes a "valueError" to be raised. Your "except" catches this and returns the message you see.

You can easily change the message (or eliminate it), but if you want to convert a word into a number you will need to use a different function to process the input. There's no built-in for this in Python itself, but some user-created modules can be found online. One example is called word2number.