Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBenjamin Dannhoff
513 PointsCode runs forever
The code ive written is verbatim that in the video. However, the loop runs on even after the tickets_remaining is at 0. Why?
TICKET_PRICE = 10
tickets_remaining = 100
while tickets_remaining: print("There are {} tickets_remaning.".format(tickets_remaining))
name = input("What is your name? ")
number_of_tickets = input(name + " how many tickets would you like to purchase? ")
number_of_tickets = int(number_of_tickets)
total = number_of_tickets * TICKET_PRICE
print("Your total is {}".format(total))
proceed = input("{}, would you like to proceed with your purchase? Yes or No? ".format(name))
if proceed == "yes":
print("SOLD!")
print("Thank you very much {}, please come back soon.".format(name))
print((tickets_remaining - number_of_tickets), "tickets are now remaning!")
else:
print("{}, thank you very much for your interest, please come back anytime.".format(name))
print("Sorry all sold out")
2 Answers
Maciej Badowski
1,842 PointsHi Benjamin, your code was running forever because (correct me if I'm wrong):
when you use
tickets_remaining - number_of_tickets
it deducts number of tickets, but does not update/save the amount in the variable tickets_remaining
, meaning that every loop runs with the re-set amount of 100 tickets_remaining
... and so this will go endless.
when you use
tickets_remaining -= number_of_tickets
it is equal to
tickets_remaining = tickets_remaining - number_of_tickets
which basically is updating/re-writing the variable on the left, i.e. tickets_remaining
with the result of the subtraction on the right (tickets_remaining - number_of_tickets
) and as such decreases with every loop
not sure if I explained it enough but feel free to ask if unclear :)
KRIS NIKOLAISEN
54,971 PointsUsually if code runs forever there is a problem with a counter or condition. You have:
tickets_remaining - number_of_tickets
whereas if you check the video @4:20 the code is
tickets_remaining -= number_of_tickets
which would decrement tickets_remaining by tickets sold each loop through
Benjamin Dannhoff
513 PointsThank you very much, revising the code to -= worked. Do you know why it wouldn't work the way I had originally wrote it?
KRIS NIKOLAISEN
54,971 PointsKRIS NIKOLAISEN
54,971 PointsCan you post your code?