# 1.4 理解Python中使用yield进行迭代

`yield`从字面意思来看，就是生产的意思，在`python`中它与`return`一样是一个关键字，也与`return`一样会返回值。但是不同于`return`的是：

1. `yield`关键字必须要配合**迭代**使用，一般使用 `for ... in ...`来进行n次迭代.
2. 如果函数`fun()`里调用了`yield`关键字则可以看成`fun()`函数`return`了n个(**取决于迭代次数**)返回值，返回值为`yield`后面的值.
3. 由于`fun()`函数是有n个返回值，所以必须使用**迭代**获取该函数的返回值，每迭代一次遇到`yield`时就返回`yield`后面(右边)的值，且很关键的是**下一次迭代时从上一次迭代遇到的**`yield`**后面的代码(下一行)开始执行**。

> 总结一句话理解`yield`就是：`yield`就是 `return` 返回一个值，并且记住这个返回的位置，下次迭代就从这个位置后(下一行)开始。

举个栗子说明：

```python
def yiled_test(n):
    for i in range(n):
        yield i*2
        # 下一次迭代时，从下面的print('i=',i)开始执行
        print('i in the yield_test',i)
    print('Finish at the end of yiled_test')

if __name__ == '__main__':
    # 必须使用迭代来获取yield_test()函数返回值
    for i in yiled_test(5):
        print('i in the main',i)
```

上面的代码运行先后顺序为：

1. 进入main中执行`yiled_test(5)`,将`5`作为形参传递给`yield_test`函数,开始执行该函数
2. 开始执行`for i in range(5)`循环迭代，第一次返回`0*2`给`main`中的循环`for i in yiled_test(5)`
3. `main`中的`i`获值为第一次返回值`0*2`, 执行`print`函数`print('i in the main',i)`
4. 继续第二次迭代，**跳回**`yield`**代码的下一行开始执行**，即`print('i in the yield_test',i)`,然后开始继续本次的迭代`yield i*2`,即返回`1*2`给`main`中的循环`for i in yiled_test(5)`,此时`i`获值为`2`
5. 依次循环迭代，直至5次迭代完成。

运行结果为：

```
$ python yield_test.py
i in the main 0
i in the yield_test 0
i in the main 2
i in the yield_test 1
i in the main 4
i in the yield_test 2
i in the main 6
i in the yield_test 3
i in the main 8
i in the yield_test 4
Finish at the end of yiled_test
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://meixuhong.gitbook.io/pythonspider/1.-zhun-bei-gong-zuo/4.-li-jie-python-zhong-shi-yong-yield-jin-hang-die-dai.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
