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

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
主站蜘蛛池模板: 浪卡子县| 抚顺县| 石阡县| 阿鲁科尔沁旗| 新密市| 枣强县| 新巴尔虎左旗| 洛南县| 叶城县| 巴南区| 广西| 炉霍县| 堆龙德庆县| 当雄县| 鄂温| 图木舒克市| 申扎县| 中方县| 调兵山市| 梁平县| 常熟市| 大悟县| 宜兰县| 镇沅| 积石山| 齐齐哈尔市| 乐清市| 大英县| 泸溪县| 商河县| 肇源县| 中阳县| 达日县| 兰州市| 遵化市| 酉阳| 大同县| 平阴县| 石景山区| 临海市| 新蔡县|