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
zoltans
2,547 PointsTo avoid the "invalid literal for int() with base 10: 'blue' message in case the user enters "blue"
Can I just not handle the error as a ValueError, as it doesn't really triggers one... Is it messy or unadvisable to handle it this way?:
TICKET_PRICE = 10
tickets_remaining = 100
while tickets_remaining:
print("There are {} tickets available.".format(tickets_remaining))
name = input("What is your name? ")
num_tickets = input("How many tickets do you need {}? ".format(name))
try:
num_tickets = int(num_tickets)
except ValueError:
print("Please enter a valid value!")
else:
if num_tickets > tickets_remaining:
print("There are only {} tickets available!".format(tickets_remaining))
else:
amount_due = num_tickets * TICKET_PRICE
print("The total cost for {} tickets is £{}.".format(num_tickets, amount_due))
confirmation = input("Would you like to continue with the purchase? Y/N ")
if confirmation.lower() == "y":
print("Sold!")
tickets_remaining -= num_tickets
else:
print("Thank you for your interest {}, good bye!".format(name))
else:
print("All tickets are now SOLD OUT! Good Bye!")
1 Answer
Steven Parker
243,266 PointsA non-numeric answer does trigger a ValueError, and this code catches it and displays "Please enter a valid value!" instead of the default "invalid literal..." message. Isn't that what you want?
And there's no problem with doing this if it's how you want the program to behave.
zoltans
2,547 Pointszoltans
2,547 PointsThank you Steven