I’m working on a program that simulates a vending machine. For some this section of my code creates an infinite loop, I cant quite figure out why. I ran it through python tutor to see where my problem was, it seems that when my variable price_remaining = 5 it will sometimes not go through the elif statement. I’m not entirely sure what would trigger it one way or another. I’m going to copy and paste what I entered in to python tutor in hopes that someone can explain based on that.
EDIT: I just checked through python tutor some more, it appears to only occur when I have a
value for price_remaining ending with a 5. For example 2.05,0.05, 1.15, etc.
price_remaining = 2.55
price_remaining = price_remaining * 100
q_stock = 25
q_returned = -0
d_stock = 25
d_returned = 0
n_stock = 25
n_returned = 0
while price_remaining > 0:
if price_remaining >=25 and q_stock > 0:
price_remaining = price_remaining - 25
q_stock = q_stock - 1
q_returned = q_returned + 1
elif price_remaining >=10 and d_stock > 0:
price_remaining = price_remaining - 10
d_stock = d_stock - 1
d_returned = d_returned + 1
elif price_remaining >=5 and n_stock > 0:
price_remaining = price_remaining -5
n_stock = n_stock - 1
n_returned = n_returned + 1
print( q_returned)
print( d_returned)
print( n_returned
)
When I add the line
at the start of your
whileloop, the code producesBecause of how floating point numbers work (see here for a reminder), you can’t always perfectly represent each possible number, hence all the 9s.
In any case, once
price_remaining < 5, even if it’s only less by a tiny amount, your code doesn’t have anyifbranch which triggers.