Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics All Together Now Handle Exceptions

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?

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?

Sorry the indenting didn't copy over as expected.

1 Answer

Steven Parker
Steven Parker
212,048 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.