当if语句为真的超过xy秒时,如何进行下一步?

时间:2018-05-02 17:05:48

标签: python python-3.x

试图找到答案,没有运气。 当if语句为真的时间超过xy秒时,如何进行下一步。

示例:

if 10 > 5 and True for 5 seconds:
    print("you did it")

这就是我的意思。修改了Rakesh的脚本以帮助像我这样的新手:

import time
import random

while True:
    blue = random.random()
    red = random.random()
    print("orange")
    print("green")
    if blue < red:  # check condition
        time.sleep(5)  # sleep 5 seconds
        if blue < red:  # check condition again
            print("you did it")  # if condition still true after 5 seconds print message
            break    # break while loop and continue with script
    else:
        continue   # if condition is not true continue with loop until condition is true

print("purple")
print("yellow")

2 个答案:

答案 0 :(得分:0)

您可以使用时间模块。

<强>实施例

import time
if (condition_if_True):
    time.sleep(5)   #Sleep 5 sec
    if (condition_if_Still_True):   #Check condition again
        print("you did it")

答案 1 :(得分:0)

循环可以有else子句,如果未执行break则会运行该子句。您可以获取当前时间并编写一个在超时时退出的while循环。如果早期满足条件,请休息一下。现在您知道else是超时。

import time
something = 10
end = time.time() + 5
while time.time() < end:
    do_something()
    if something < 5:
        print("exit early")
        break
else:
    print("you did it")