Reputation: 586
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? And how would you have the code re-run its self using "return" as opposed to "print"??
Thanks ya"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()
Upvotes: 0
Views: 618
Reputation: 226256
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.
The return exits the function entirely so that it cannot be restarted.
Q.
And how would you have the code re-run its self using "return" as opposed to "print"?
Use "yield" instead of "return" to create a kind of resumable function called a generator.
For example:
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)
Upvotes: 3
Reputation:
return s
returns from stop()
. It does not continue
the while
loop. If you want to stay in the loop, don't return from the function.
Upvotes: 4