官术网_书友最值得收藏!

How to create a generator in Python?

Creating a generator is easy in Python. You can create a generator just by defining a function with a yield statement instead of a return statement. If a function contains at least one yield statement, it becomes a generator function. yield and return statements will return some value from a function. Here is an example:

def my_gen():
n = 1
print('This is printed first')
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
for item in my_gen():
print(item)

Output:
This is printed first
1
This is printed second
2
This is printed at last
3
主站蜘蛛池模板: 盐亭县| 洛川县| 象州县| 申扎县| 阳新县| 化隆| 定远县| 榆林市| 石台县| 汉川市| 象州县| 沙河市| 正定县| 林口县| 海城市| 滦平县| 阳西县| 鹤壁市| 南丰县| 红河县| 碌曲县| 达孜县| 宁化县| 那曲县| 安图县| 定西市| 辰溪县| 介休市| 抚松县| 孟津县| 清水河县| 旌德县| 高淳县| 乌拉特中旗| 金寨县| 大田县| 灌阳县| 蕲春县| 定襄县| 利辛县| 华宁县|