Python Python Basics All Together Now Branch and Loop

2 Answers

Josh Keenan
Josh Keenan
19,382 Points

So I refined it into this:

TICKET_PRICE = 10
tickets_remaining = 100  

while tickets_remaining > 0:
  name = input("What's your name? ")
  print("There are {} tickets left.".format(tickets_remaining))
  tickets = int(input("How many tickets would you like to buy? "))
  if tickets > tickets_remaining:
    print("You can only buy up to {} tickets!".format(tickets_remaining))
  else:        
    price = tickets * TICKET_PRICE
    tickets_remaining = tickets_remaining - tickets
    print("You bought {} tickets for ${}".format(tickets, price))
    print("There are {} tickets left.".format(tickets_remaining))
    if tickets_remaining <= 0:
      break

I'll explain the issues you had, and how this works.

Your issue was using a new variable at the end to save the number of tickets left, it wouldn't pass back around to the loop when it started a new iteration, it would just save the new number of tickets to newTotalTickets, but the number used in the rest of the loop was tickets_remaining, which meant that tickets_remaining would just stay at 100. You also didn't limit how many tickets could be bought so it would accept 101.

In the version I have made, it prevents the user buying more tickets than are available with the if statement. If the purchase is valid we move to the else clause, and it calculates the new total, and if that's below 1 then ends the program.

Hope this makes sense and feel free to ask any questions!

Jeremiah Marcos
Jeremiah Marcos
2,339 Points

ooh! okay thank you very much i get it now, after the (break) that is where you put the print statement saying that the tickets are sold out. so where i was wrong is i didn't update the tickets_remaining value and didn't set a limit i know it may sounds like i'm just repeating my self, but i saw where I was wrong now

Josh Keenan
Josh Keenan
19,382 Points

I have full faith in you! You got this!