I've got a very basic generator where you can send during the loop a new value through the yield callback:
def GenInter(x, y):
while (x+1 < y):
callback = (yield x)
if callback is not None:
x = callback
else:
x += 1
Then, I create a generator:
myGen = GenInter(10,25)
And finally, I'm parsing it with a for loop. When it's "15", I want to go directly to "20".
for x in myGen:
if x == 15:
myGen.send(20)
print(x)
Here is the result:
10
11
12
13
14
15
21
22
23
How come the "20" value is missing?
Thank you for your help.
The problem is that the send
call actually runs an iteration and returns a value and you aren't doing anything with it.
Try this:
print(myGen.send(20))
As pointed out by @Imreal and by @Abarnert, myGen.send(20)
yields the missing 20. You can resolve your issue by changing your iteration to this:
for x in myGen:
y = x
if x == 15:
y = myGen.send(20)
print(y)
It returns the following output:
10
11
12
13
14
20
21
22
23
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.