Reputation: 56
When i run my code, the number turns into 42.0 (what it's supposed to do) but does not stop when it turns into 42.0 (though the if statement or while loop) how would i get my code to stop?
import time
def life(inp):
inp = float(inp)
while float(inp) != float(42):
inp = inp*12/4/4+4+6.5
if float(inp) == float(42) or inp == 42:
print inp
break
print inp
time.sleep(0.1)
life(6)
Upvotes: 1
Views: 134
Reputation: 28596
Because it isn't 42.0, which you can see by doing print '%.60f' % inp
instead. Then you'll see that you're actually stuck at 41.999999999999985789145284797996282577514648437500000000000000.
Or with print repr(inp)
, which shows 41.999999999999986 (not the exact stored value, but it shows that it's not 42.0).
If you just do print inp
or print str(inp)
then Python shows a "nice version" of the number, which doesn't necessarily actually represent the number.
You might want to go for "close enough" instead, for example like this:
while abs(float(inp) - float(42)) > 1e-9:
Or check out this answer.
Upvotes: 13