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 trial

Python Python Basics All Together Now Handle Exceptions

Thomas Greer
Thomas Greer
1,472 Points

How do I get different error codes based on different user input?

What am I missing here?


tickets_remaining = 100

while tickets_remaining >= 1: print("There are only {} tickets remaining. Buy them fast!".format(tickets_remaining)) name = input("What is your name? ")

number_of_tickets = input("Hey {}, how many tickets would you like to buy?  ".format(name))

    number_of_tickets = int(number_of_tickets)
    if number_of_tickets > tickets_remaining:
        raise ValueError("There are only {} tickets remaining".format(tickets_remaining))
except ValueError as err:
    print("Uh oh! We ran into an issue. {}. Please try again".format(err))
    total_due = number_of_tickets * TICKET_PRICE
    confirm = input("{}, your total will be {} for {} tickets. Would you like to proceed? Y/N  ".format(name, total_due, number_of_tickets))
    if confirm.lower() == "y":
        # TODO: Gasther credit card information and process it.
        print("SOLD! Thank you for your purchase!")
        tickets_remaining -= number_of_tickets
        print("Thanks anyway, {}!".format(name))

print("There are no more tickets remaining. Sorry!")

Everything runs as it should except when the user types in a non numerical value they get the error: "Uh oh! "We ran into an issue. invalid literal for int() with base 10: 'blue'. Please try again "

1 Answer

Steven Parker
Steven Parker
229,921 Points

The message is also "running as it should". Performing the "int" function on the input raises a ValueError when the input contains something other than a number. Then the print formatting includes the system error text into the message. The system text correctly (if perhaps a bit over-technically) identifies the reason for the error.

You might want to look at some of the other questions asked about this video (under the "Questions" tab near the bottom of the page). Several of the answers contain suggestions for alternative ways to respond to the error.