- Mastering Python Scripting for System Administrators
- Ganesh Sanjiv Naik
- 114字
- 2021-07-02 14:00:29
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
推薦閱讀
- Facebook Application Development with Graph API Cookbook
- 數字媒體應用教程
- The Modern C++ Challenge
- 精通軟件性能測試與LoadRunner實戰(第2版)
- Building Mapping Applications with QGIS
- Learning OpenStack Networking(Neutron)
- Android開發三劍客:UML、模式與測試
- 軟件供應鏈安全:源代碼缺陷實例剖析
- Scratch趣味編程:陪孩子像搭積木一樣學編程
- C++程序設計教程(第2版)
- ASP.NET 4.0 Web程序設計
- PHP 8從入門到精通(視頻教學版)
- Visual Basic 程序設計實踐教程
- C# 7 and .NET Core 2.0 Blueprints
- Python網絡爬蟲從入門到實踐