Python Python Basics All Together Now Branch and Loop

This script can sell more than 100 tickets

I'm looking at the Branch and Loop section with Craig Dennis. He demonstrates a working script where 98 and 2 sells 100 tickets. It should not be able to sell more than 100. However, if you enter 98 and 3, it will not catch that you went over. It will sell 101 tickets which exceeds the total number of tickets. I believe you can catch this with a while loop.

num_tickets = int(input("How many tickets would you like?  "))
while num_tickets>tickets_remaining:
    num_tickets = int(input("The number of tickets remaining is {}.  How many would you like?  ".format(tickets_remaining))

3 Answers

Marcos Lisboa
Marcos Lisboa
6,000 Points

Here is how I manged this:

TICKET_PRICE = 10

tickets_remaining = 100

name = input("What your name?  ")

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

    tickets_wanted = int(input("Hi, {}! How many tickets you would like to buy?  ".format(name)))

    while tickets_wanted > tickets_remaining:
        print("Sorry {}. We don't have the desired ammount of tickets.".format(name))
        tickets_wanted = int(input("How many tickets you would like to buy {}?  ".format(name)))

    total_price = float(TICKET_PRICE * tickets_wanted)


    print("The total cost will be: ${}".format(total_price))


    decision = input("Would you like to proceed with the purchase of {} tickets for ${}?  \n(Enter Y or N)  ".format(tickets_wanted, total_price))

    if decision == "Y" or decision == "y" or decision == "YES" or decision == "yes":
        print("SOLD!")
        tickets_remaining -= tickets_wanted
    else:
        print("Thanks for your interest {}".format(name))
else:
    print("Tickets SOLD OUT!")
Radu Pacurar
Radu Pacurar
12,051 Points

Hey, I`m just a new-bee, but I think that in the while loop you must have a way to decrement "tickets_remaining". Something like "tickets_remaining = tickets_remaining - num_tickets"

jopapadaki
jopapadaki
7,281 Points

Yes, if put the tickets to not be 0, it works with negative results, for example, you sell 98, then 2, then you sell 1 and it says there is -1 tickets & keeps going on, looping forever till you write a string & gives type error.