K
K
Kit Scribe2021-08-24 19:12:26
Python
Kit Scribe, 2021-08-24 19:12:26

Why does the generator return an incorrect value?

There is such

the code
def test_gen():
    value = yield
    end = value + 20

    while True:
        if value > end:
            break
        yield value
        value += 1

mygen = test_gen()
next(mygen)
mygen.send(10)

for item in mygen:
    print(item)


I expect the iteration to start at 10 and end at 30, but I get the following
conclusion
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30


Why does it happen this way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-08-24
@kitscribe

Because .send() not only passes the value inside the generator, but also returns the next yielded value.

mygen = test_gen()
next(mygen)
print('Send:', mygen.send(10))

will output Send: 10.
So you have to do another intermediate yield None right after getting value = yield.
Well, yes, why break when you can make a condition in while?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question