Reputation: 83
I am trying to stop a while loop in the middle and my code is:
import time
now = time.time()
future = now + 1.8
while time.time() < future:
time.sleep(2) # acts as instructions and code
print("Still in")
print("Now out")
I don't want it to print "Still in" as the time limit would have been exceeded but it continues the loop till the end. This is an example code.
Upvotes: 0
Views: 1139
Reputation: 1019
you can check the condition after time.sleep()
and break
out of while
before reaching the rest of the block
import time
now = time.time()
future = now + 1.8
while True:
time.sleep(2) # or any code that affects your condition
if time.time()>= future: #if this happens break the loop, if not continue
break
print("Still in")
print("Now out")
Upvotes: 0