Python Python Basics All Together Now Handle Exceptions

faizel khan
PRO
faizel khan
Pro Student 4,355 Points

If raise not working with same code

TICKET_PRICE = int(10)

tickets_remaining = int(100)

while tickets_remaining >0:
    print ("Remaining tickets are {}".format(tickets_remaining))

    name = input("What is your name?  ")

    ticket_required = input("Hom many tickets your what {}".format(name))
    try:
        ticket_required =int(ticket_required)
        if ticket_required > tickets_remaining:
            raise ValueError("wrong quantity")
    except ValueError as err:
        print("Error:{} please enter valid ticket".format(err))
    else:
        price= ticket_required*TICKET_PRICE
        print ("{} your total bill is ${}".format(name,price))

        confirmation = input("would you like to continue y/n")

        if confirmation == "y":
            print("SOLD {} tickets to {} for ${}".format(ticket_required,name,price))
            tickets_remaining -= ticket_required
            print ("Remaining tickets are {}".format(tickets_remaining))

        else: print ("thank you for your enquiry {}".format(name))
print("we are sold out")

MOD: I just added some formatting to make your code easier to read, and easier for people to help you. Please see the Markdown Cheatsheet below the text boxes to see how to do this. Thanks! :-)

Louise St. Germain
Louise St. Germain
Treehouse Moderator 12,228 Points

Hello Faizel,

Can you tell me more about the problem you are having? I tried running your code and it seems to be working...

2 Answers

Mark Chesney
Mark Chesney
10,926 Points

On the contrary to Louise St. Germain , when I ran the above code I fell into an infinite loop (if anyone does, hit CTRL+C to exit)

Louise St. Germain
Louise St. Germain
Treehouse Moderator 12,228 Points

Hi Mark,

Interesting... what kind of infinite loop? i.e., what triggers it? So far I've tried a few different things but nothing has caused an infinite loop so far. (The message with # of remaining tickets does appear twice, which is a bit odd, but doesn't break anything.)

Mark Chesney
Mark Chesney
10,926 Points

Hi Louise, sorry for my delay. Yes, when I copy the code block into my terminal I see an infinite loop of this:

Remaining tickets are 100
Remaining tickets are 100
Remaining tickets are 100
Remaining tickets are 100
Remaining tickets are 100
Remaining tickets are 100
Remaining tickets are 100
Remaining tickets are 100

I'm curious what others experience.

Louise St. Germain
Louise St. Germain
Treehouse Moderator 12,228 Points

Hi Mark,

Hmm, very interesting! I'm not even sure how that infinite loop would happen (though I trust you that it does), since the very next line is a non-optional request for input. Are you sure it's grabbing the whole block of code? The only way I can replicate that loop is by copying only the first 4 (non-blank) lines of code.

Anyway, I'd also be curious to hear what happens when others run the code!