我想将下面的代码的答案返回给变量,变量应该每5秒更改一次,因此我不能使用'return',因为它结束了该函数。如何在不结束Python函数的情况下返回变量变量?
例如:
from time import sleep
def printit():
cpt = 1
while True:
if cpt < 3:
number = ("images[" + str(cpt) + "].jpg")
return number #here is the return
sleep(5)
cpt+=1
else:
printit()
answer = printit()
print(answer) #only 1 answer is printed, then the function ends because of the 'return'
什么是解决这一问题的解决方案?
变量答案应每5秒更换一次而不终止该功能。
一种用于发电机的工作https://wiki.python.org/moin /发电机或关闭http://www.shutupandship.com/2012/01/python-closures-explained.html?m=1 – dylan7