Epic Boss
Epic Boss

Reputation: 83

Stopping a while loop in the middle after time limit exceeded without continuing the loop to the end

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

Answers (1)

mehrdadep
mehrdadep

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

Related Questions