Python Python Basics All Together Now Handle Exceptions

Abdullah Jassim
Abdullah Jassim
4,551 Points

How do I modify this to capture errors: 1) num of ticket should be an int 2) number less than tickets remaining?

Right now it only captures one error which is ticket purchased should not equal tickets remaining.


tickets_remaining = 100  

while tickets_remaining >= 1:
    print("There are {} tickets remaining".format(tickets_remaining))
    first_name = input("What is your name? ")
        tickets_to_buy = int(input("Welcome {}! How many tickets do you wanna buy? ".format(first_name)))
        if tickets_to_buy > tickets_remaining:
            raise ValueError ("There are only {} remaining {}".format(tickets_remaining, first_name))
    except ValueError as err:
        print("Oh no, we ran into an issue.{}. Please try again".format(err))
        price = tickets_to_buy * TICKET_PRICE
        print("Your price is ${} USD".format(price))
        proceed = input("Do you want to proceed? (Y/N) ")
        if proceed.lower() == "y":
            #Print SOLD and gather credit card information
            tickets_remaining -= tickets_to_buy
            print("You have {} tickets remaining".format(tickets_remaining))
            print("Thank you for coming {}".format(first_name))
            print("You have {} tickets remaining".format(tickets_remaining))

print("Sorry tickets are sold out")

1 Answer

Steven Parker
Steven Parker
168,628 Points

It looks like it will already capture an error if you put in a number of tickets that is not an integer.

For example, if you put in "3.5", you should see "Oh no, we ran into an issue.invalid literal for int() with base 10: '3.5'"