在 python 中使用 time.sleep 打印 vs Return

Print vs Return with time.sleep in python

谁能给我解释一下为什么后面用"print"会继续重运行代码,而用"return"只会运行一次?您如何使用 "return" 而不是 "print" 来重新 运行 自身的代码??

谢谢你们!

def stop():
    while True:
        oanda = oandapy.API(environment="practice", access_token="xxxxxxxx")
        response = oanda.get_prices(instruments="EUR_USD")
        prices = response.get("prices")
        asking_price = prices[0].get("ask")
        s = asking_price - .001
        print s
    time.sleep(heartbeat)


print stop()

VS

def stop():
    while True:
        oanda = oandapy.API(environment="practice", access_token="xxxxxxxxxx")
        response = oanda.get_prices(instruments="EUR_USD")
        prices = response.get("prices")
        asking_price = prices[0].get("ask")
        s = asking_price - .001
        return s
    time.sleep(heartbeat)


print stop()
return s

return 秒来自 stop()。它 而不是 continue while 循环。如果您想留在循环中,请不要从函数中 return。

Q.

Can someone explain to me why using "print" in the following will continue to re-run the code, but using "return" will only run it once?

A.

return 完全退出函数,无法重新启动。

Q.

And how would you have the code re-run its self using "return" as opposed to "print"?

使用"yield" instead of "return" to create a kind of resumable function called a generator.

例如:

def stop():
    while True:
        oanda = oandapy.API(environment="practice", access_token="xxxxxxxx")
        response = oanda.get_prices(instruments="EUR_USD")
        prices = response.get("prices")
        asking_price = prices[0].get("ask")
        s = asking_price - .001
        yield s

g = stop()
print next(g)
print next(g)
print next(g)