This document explores the use of the yield keyword. This command exists in other languages too (C# and .NET among them). Code in the next cell was excerpted from a StackOverflow post. Comments were then added after running a quick test.
In [2]:
def f123():
yield 1
yield 2
yield 3
for item in f123():
print(item) # by iterating over the "generator object" this function returns, we see the answers
# yield is adding results into a generator object that the function will then return
In [3]:
f123() # note: returns a generator object that each yield added content to
Out[3]:
Here's another demo from StackOverflow showing that a function using yield does not have to terminate and can be used in code as shown here. Author indicates this can help solve certain tricky situations. Testing and experimentation with this has not been undertaken yet.
In [5]:
def fib():
last, cur = 0, 1
while True:
yield cur
last, cur = cur, last + cur
def psuedo_code_doNotRunWithoutFixingIt():
some_condition = False # added so this cell won't throw an error
# edit and implement what follows to make use of this example
for f in fib():
if some_condition: break
# coolfuncs(f); # do something here ... author wrote it as coolfuncs(f);
In [4]:
# implementing the pseudocode just to show it in action ...
# this may not represent best practice but could be useful in the field ...
def fib():
last, cur = 0, 1
while True:
yield cur
last, cur = cur, last + cur
def x_toThe_x(x):
return x**x
def testCodeFor_fib():
some_condition = 13
loopCount = 0
for f in fib():
print("Starting loop %d with f of %d." %(loopCount, f))
if f >= some_condition:
print("Termination point reached, exiting loop.")
break
print("%d raised to the %d power: %d" %(f,f, x_toThe_x(f))) # do stuff here, this is an example
loopCount +=1
# test the code
testCodeFor_fib()
In [ ]: