Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDanny Rosenbaum
767 PointsThe 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.
Danny Rosenbaum
767 PointsThe 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
767 PointsSorry the indenting didn't copy over as expected.
1 Answer
Steven Parker
231,268 PointsThe "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.
Lucas Taylor
125 PointsLucas Taylor
125 PointsCan you please post an example or piece of the code?