Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python generator yield statement not yield

Here is code I am running:

def infinite_Third() -> Generator:
    num = 1
    while True:
        if num % 3 ==0:
            i = (yield num)
            if i is not None:
                num = i
        num += 1 

if __name__=='__main__':
    third_gen = infinite_Third()
    for i in third_gen:
        print(f"it is {i}")          
        if i>1000:
            break    
        third_gen.send(10*i+1) 

I am expecting to see results as:

it is 3
it is 33
it is 333
it is 3333

However, what I really get is:

it is 3
it is 36
it is 366
it is 3666

I think this might be related to using send in the main code, but couldn't figure out why. Can anyone help?

like image 374
datapy Avatar asked Nov 06 '22 11:11

datapy


1 Answers

Follow up from my comment, I've modified your main loop

  • First, we send a None to start the generator and receive the first value
  • After that, we send one value and receive the next one
if __name__ == '__main__':
    third_gen = infinite_Third()
    i = third_gen.send(None)
    while True:
        print(f"it is {i}")
        i = third_gen.send(10*i+1)
        if i > 1000:
            break
like image 148
JoseKilo Avatar answered Nov 14 '22 22:11

JoseKilo