A problem with python generator interaction?

in python interaction mode, there is the following code:

def squares(cursor=1):
    response=None
    while True:
        if response:
            response=yield response**2
            continue
        response=yield cursor**2
        cursor+=1

sq=squares()
>>> next(sq)
1
>>> next(sq)
4
>>> sq.send(7)
49
>>> next(sq)
9
The

question is as follows:
Why is response not assigned to 1 after calling next (sq) for the first time? (because the result of the second call to next is 4)

when sq.send (7) is called for the first time, is response assigned to 7? Why is it that the result of calling next again is still 9?

Mar.05,2021

has just written an article about yield, which can be referenced by the landlord.

python-material-collection/blob/master/examples/yield.md" rel=" nofollow noreferrer "> what exactly does it do when we call yield,

write something about my understanding:

when sq.send (7) is called for the first time, the code executes to:

response=yield cursor**2

at this point, the value of response is 7, and then execute

cursor+=1 -sharp cursor3

then go on to the next loop, at this time:

if response:
  response = yeild response*2

returns 49, and then when you type next (sq), response is not explicitly assigned, so response becomes None; and then runs:

continue

then go down normally.


1    def squares(cursor=1):
2        response=None
3        while True:
4            if response:
5                response=yield response**2
6                continue
7            response=yield cursor**2
8            cursor+=1

(1) the first call to next (sq), hangs at position 7, waiting for you to pass a value through send, and the returned cursor**2, is 1.

(2) when you call sq.send (7), the generator hangs at position 7, passing in 7, that is, assigning a value of 7 to response, loop, arriving at position 4, entering the if statement and returning 7 7, that is, 49. The generator hangs at position 5 and calls next (sq), continue, again to return the first sentence of the loop, that is, position 3. Without passing send, the generator assigns None to the response, with a value of 7. Finally, as above, it hangs at position 7, and returns the previous cursor 2, that is, 9

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b37170-e5b6.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b37170-e5b6.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?