2015-04-28 53 views
0

有人可以向我解释为什么在下面使用“print”会继续重新运行代码,但使用“return”将只运行一次?你将如何使用“返回”而不是“打印”来重新运行自己的代码?打印vs带time.sleep的python返回

感谢雅“LL!

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() 
+0

如果while循环,除非使用'break'声明 – logic

回答

3

问:

能有人为什么在以下 使用“打印”将继续重新运行代码,但使用“返回”向我解释,将只运行一次?

A.

return退出完全是这样的,它无法重新启动的功能。

问:

你会怎么让代码重新运行使用 “回归”,而不是“打印”自身?

使用"yield"代替“返回”来创建一种名为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) 
+0

That's awesome @Raymond Hettinger!非常感谢,我现在正在处理'收益'! – MacD

4
return s 
stop()

回报。它确实continuewhile循环。如果你想留在循环,不要从功能返回。

+0

所以你不能在使用“回归”不要用'return',你可以有效地创建无限一个循环?谢谢你的回答。 – MacD

+0

当然你可以。但这取决于你想要做什么。你想要一个无限循环吗?然后不要回来。如果你想在某个时候退出循环,检查一个条件并返回。 – 2015-04-28 15:15:20

+1

这是因为你在函数中使用'return',它与循环无关。 'return'总是结束它所在的函数,循环或不循环。 – SuperBiasedMan