1

The goal is that when sleep_time reaches 0.1 it starts a loop where it prints number.

import time

number = 0
sleep_time = 1

# Main code
while sleep_time >= 0.1:
    if sleep_time == 0.1:
        while True:
            print(number)
    number += 1
    time.sleep(sleep_time)
    print(number)
    sleep_time -= 0.1

This prints numbers from 1 to 10 and then it stops.

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
VittorioDL
  • 39
  • 5

2 Answers2

4

This is an issue of floating-point imprecision, consider:

>>> sleep = 1
>>> dec = 0.1
>>> for _ in range(9):
...     sleep -= dec
...
>>> sleep
0.10000000000000014
>>> sleep == 0.1
False
>>>

When dealing with this sort of thing, usually math.isclose is a viable solution:

>>> import math
>>> math.isclose(sleep, 0.1)
True
>>>

The following should be required reading

Other approaches would be to use only int objects, or to use decimal.Decimal.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
1

This is due to floating point error.

x = 1.0
for _ in range(9):
    x -= 0.1

print(x) # 0.10000000000000014
print(x == 0.1) # False

When exact arithmetic is required for a problem which handles an atomic quantity, it's better to use int than float. In this case your atomic quantity being a tenth of a second, we'll let 1 represent 0.1 second.

import time

number = 0
sleep_time = 10 # in tenth of seconds

# Main code
while sleep_time >= 1:
    if sleep_time == 1:
        while True:
            print(number)
    number += 1
    time.sleep(sleep_time / 10)
    print(number)
    sleep_time -= 1
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73