我想將下面的代碼的答案返回給變量,變量應該每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