Python programming must know: the application of return and yield, the difference is revealed even for beginners

In Python, both return and yield can be used to return values ​​in functions, but there is a big difference between them. Insert image description here

returnThe statement is used to return a value from a function and terminate the execution of the function. When the function reaches the return statement, it stops immediately and returns a value. In a function, the return statement can appear multiple times, but the value will only be returned the first time it appears. If no return value is specified, it defaults to None.

yieldThe statement is used to define a generator function. A generator function is a special function that pauses execution and returns an intermediate result, then resumes execution when needed. When the function executes to the yield statement, it will return a value and pause execution, waiting for the next call to continue execution. In a function, the yield statement can appear multiple times, each time returning a value. Generator functions can be used in iterators, and the values ​​returned by the generator function can be obtained one by one through for loops or next() functions.

Thus, the main difference between return and yield is: return statement is used to return a value from a function and terminate The execution of the function, and the yield statement is used to define the generator function, which can pause execution and return an intermediate result.

The following is a simple example demonstrating the difference between return and yield:

# return语句的例子
def func_return():
    print("start")
    return 1
    print("end")  # 这行代码不会执行

result = func_return()
print(result)  # 输出:1

# yield语句的例子
def func_yield():
    print("start")
    yield 1
    print("middle")
    yield 2
    print("end")

gen = func_yield()
print(next(gen))  # 输出:1
print(next(gen))  # 输出:2

Guess you like

Origin blog.csdn.net/u014740628/article/details/134822822