簡體   English   中英

在python中打印vs返回time.sleep

[英]Print vs Return with time.sleep in python

有人可以向我解釋為什么在下面使用“打印”將繼續重新運行代碼,但是使用“返回”將僅運行一次嗎? 以及如何使用“ 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

stop()返回。 continuewhile循環。 如果要停留在循環中,請不要從函數中返回。

有人可以向我解釋為什么在下面使用“打印”將繼續重新運行代碼,但是使用“返回”將僅運行一次嗎?

一種。

返回值完全退出該函數,因此無法重新啟動它。

您將如何使用“返回”而不是“打印”來重新運行自身的代碼?

使用“ yield”而不是“ return”來創建一種稱為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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM