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

Alan Aranga
Alan Aranga
6,010 Points

Raising Exceptions...

TICKET_PRICE = 10

def price_calculator(TICKET_PRICE, number_of_tickets): if number_of_tickets <= 0: raise ValueError("Tickets ordered have to be more that 0. Please try again.") elif number_of_tickets > tickets_remaining: raise ValueError("Sorry {}, there are only {} tickets remaining. Please try again.".format(name, tickets_remaining)) return TICKET_PRICE * number_of_tickets

tickets_remaining = 100 while tickets_remaining > 0: name = input("Hi, What is your name? ") print("Hi {}, there are {} tickets remaining.".format(name, tickets_remaining)) try: number_of_tickets = int(input("How many tickets would you like {}? ".format(name))) cost = price_calculator(TICKET_PRICE, number_of_tickets) except ValueError as err: print("Oh no, we ran into an issue. Please try again.") print("{}".format(err)) else: print("The total due is ${}.".format(cost)) decision = input("Would you like to proceed with the purchase?\n(Enter Y/N)") if decision.lower() == "y": print("SOLD!! Enjoy the show {}.".format(name)) tickets_remaining -= number_of_tickets else: print("Thank you for your time {}.".format(name)) print("Sorry, all the tickets are sold out!😭")

I opted to use a function for this command line application. I thought I handled all the exceptions but whenever a user enters a string for the 'number_of_tickets_variable' I keep getting this error in the console: "invalid literal for int() with base 10: 't'". Is there any change I can make to this code to handle the error in a user-friendly manner?

Alan Aranga
Alan Aranga
6,010 Points

Sorry the code is all jumbled up, I didn't know how to add the workspaces bit...

1 Answer

Steven Parker
Steven Parker
231,248 Points

That's the correct system error message, though as you point out it's not terribly "user friendly". But you can show anything you like:

#   print("{}".format(err))                          # so instead of the system error
    print("Be sure to enter a number this time!")    # you could show something else