「Python3.9」ジェネレータを使うサンプル
環境
Python 3.9.13
Windows 11 Pro 21H2 64bit
PyCharm 2022.2.1 (Community Edition)
構文
def 関数名()
yield “文字列"
変数名 = 関数名()
関数内にキーワードのyieldを記述します。
yield文は値を返します。
関数を呼ぶ側は、next関数で呼び出します。
使用例
# coding: utf-8
def funa():
yield "study"
yield "skill"
# 定義した関数を変数に代入
res = funa()
#next関数でfuna関数を実行
print(next(res))
print(next(res))
実行結果
study
skill