I'm studying in Python yield
and find that yield
is not only the way in which generators output a return value but also a way to put values into a generator. For example the following code
def f():
print (yield),
print 0,
print (yield),
print 1
g = f()
g.send(None)
g.send('x')
g.send('y')
In the global scope it send
s value 'x'
, 'y'
to the generator and thus in f
it will output x 0 y 1
. But I cannot understand
- There are 2
yield
s but 3send
s. Why should it sendNone
at the first time? - It throws a
StopIteration
at the lastsend
. Is there any way to avoid this exception?
Could anyone please explain that? Thanks in advance.