Python Python Basics All Together Now Handle Exceptions

Adam Franklin
Adam Franklin
1,261 Points

Why won't my ValueError is the tickets are greater than the remaining tickets run?

My code seems to just jump to the except ValueError rule instead of executing my raise ValueError if num_tickets > tickets_remaining.

Any help would be appreciated.

while tickets_remaining >= 1: users_name = input("Hi! What is your name? ") num_tickets = input("Hi {}! How many tickets would you like? ".format(users_name)) #expect a ValueError to happen and handle it. try: num_tickets = int(num_tickets) if num_tickets > tickets_remaining: raise ValueError("There are only {} tickets remaining".format(tickets_remaining)) #raise a ValueError if the request is for more tickets than are available except ValueError as err: print("Oh no, we ran into an error! Please try again".format(err )) else: total_price = (num_tickets * TICKET_PRICE) print("Adam, your total will be ${} ".format(total_price)) confirm = input("Would you like to proceed? Y/N ") if confirm.upper() == "Y": print("Sold!!! ")

KRIS NIKOLAISEN
KRIS NIKOLAISEN
Pro Student 50,001 Points

Can you format your code with markdown or post it as a workspace snapshot?

1 Answer

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 50,001 Points

It does run. But there is no placeholder in the following string for the error message

"Oh no, we ran into an error! Please try again".format(err )

Replace that with this and you will see the message

"Oh no, we ran into an error! {}. Please try again".format(err )
Adam Franklin
Adam Franklin
1,261 Points

Thank you. This worked now and I was missing the placeholder.

Steven Parker
Steven Parker
174,163 Points

I also noticed that tickets_remaining is not being reduced on a successful sale, so only a single sale larger than the starting total would raise an error.

And as long as you purchase smaller amounts, there's an infinite supply of tickets! :wink: