yield of understanding - Python

yieldIn addition there is a keyword meaning the meaning of return, as well as temporary storage when running to yield, it returns the current value, and then save the current record. When you run the functional again, continue to the end of the last yield location started running.

Deep understanding, for reference only

Example one


def foo(num):
    print("starting...")
    while num < 10:
        num = num + 1
        yield num


# debug看运行顺序 即可
for n in foo(0):
    print(n)

Here Insert Picture Description

Example Two


def gen(n):
    for i in range(n):
        yield i ** 2


for i in gen(5):
    print(i, " ", end="")

Here Insert Picture Description

He published 190 original articles · won praise 153 · views 90000 +

Guess you like

Origin blog.csdn.net/qq_36852780/article/details/104506475