power
has ayield
return, which makes it agenerator
. The code in the function itself is only execute whennext()
is called on it.- correct.
adder
relies on the generator, and has no information on the data being iterated. (such as the size) - correct again
yield
is a particular instruction. It does not return from the generator function (power
). Instead, it provides one value, and suspend its execution until the next call tonext()
. At this point, the execution is resumed at the same point, which is inside the loop.
Edit
Illustration of the yield
stopping point:
def gene():
print 'first!'
yield 1
print 'second!'
yield 2
g = gene()
g.next()
# first!
# 1
g.next()
# second!
# 2
As you can see, the generator is interrupted exactly after the yield
instruction, ready to execute the next one