总睡眠时间应为60秒,并且每次检查的间隔应为5秒。 我应该如何使用count变量来跟踪总执行次数
def test(a):
count=0
while True:
if a < 10:
print("ok")
return True
count = count+1
time.sleep(5)
if(count == 12):
return False
print(test(a=40))
while循环应在60秒后停止执行并返回false,每个检查间隔为5秒。我感到困惑,我应该在time.sleep(5)之前还是time.sleep(5)之后增加计数。看到time.sleep被执行了12次并且等待了60秒并返回false,该怎么办?
答案 0 :(得分:0)
import time
def test(a):
count=0
while True:
if a < 10:
print("ok")
return True
count = count+1
time.sleep(5)
if(count == 12):
return False
print ("Start : %s" % time.ctime())
print(test(a=40))
print ("End : %s" % time.ctime())[enter image description here][1]
答案 1 :(得分:0)
您可以使用time.time()
import time
max_time = 60
start_time = time.time() # remember when we started
def test(a):
count=0
while (time.time() - start_time) < max_time:
if a < 10:
print("ok")
print(test(a=40))