超过时间限制后在中间停止while循环而不继续循环到结束

问题描述 投票:0回答:1

我试图在中间停止一个while循环,我的代码是:

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")

我不希望它打印“仍在”,因为时间限制已被超过但它继续循环直到结束。这是一个示例代码。

python loops
1个回答
0
投票

你可以检查time.sleep()break之后while的状况,然后到达剩下的区块

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")
© www.soinside.com 2019 - 2024. All rights reserved.