Let's trace the operation a little more closely:
def monG(borneinf,bornesup):
while True:
if bornesup < borneinf:
bornesup, borneinf = borneinf, bornesup
borneinf += 1
if borneinf==bornesup:
break
print("TRACE", borneinf, bornesup)
x=(yield borneinf)
if x is not None:
borneinf = x
c = monG(2,10)
print(type(c))
for a in c:
if a==5:
print(c.send(20), "a==5")
print(a)
This gives us a special tag on the c.send
line, as well as a peek just before the yield
Output:
<class 'generator'>
TRACE 3 10
3
TRACE 4 10
4
TRACE 5 10
TRACE 11 20
11 a==5
5
TRACE 12 20
12
TRACE 13 20
13
TRACE 14 20
14
TRACE 15 20
15
TRACE 16 20
16
TRACE 17 20
17
TRACE 18 20
18
TRACE 19 20
19
As MisterMiyagi
pointed out, yield
does return 11, but you threw it away. Perhaps you wanted to assign that value to a
-- although messing with loop parameters is a definite code smell. If you make that assignment, you print out 11
instead of 5
on that iteration.
I think that your basic problem is that you interfered with your iteration flow, forcing an extra yield
inside the loop. In the loop you coded, that implicit yield
means that you don't get both 5
and 11
on successive iterations.