Python 3: print と return について(超基礎)
print()
とreturn
について
関数の定義でprint()
とreturn
どちらをつかうべきか?
print()
・・・表示するだけreturn
・・・戻り値を返す
>>> def print_hello(): ... print("hello") ... >>> print_hello() hello
>>> def return_hello(): ... return "hello" ... >>> return_hello() 'hello' >>> print(return_hello()) hello
ジェネレータ関数で理解を深める
- ジェネレータ関数では,
return
の代わりにyield
を用いる - ジェネレータ関数を定義して,イテレータのように値を次々を取り出せるオブジェクトを作ることができる
Question:range(10)
から奇数を返すodds
というジェネレータ関数を定義し,返された3番目の値を見つけて表示せよ.
odds()
を実行するとジェネレータ・オブジェクトであることが分かる.
>>> def odds(): ... for num in range(1, 10, 2): ... yield num ... >>> for count, number in enumerate(odds(), 1): ... if count == 3: ... print(number) ... break ... 5
odds2()
では,return
によってfor
文で現れる最初の値が返される.odds2()
はint
型であることが分かる
>>> def odds2(): ... for num in range(1, 10, 2): ... return num ... >>> odds2() 1 >>> odds2() 1 >>> for count, number in enumerate(odds2(), 1): ... if count == 3: ... print(number) ... break ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable
odds3()
ではprint()
によって1から10までの奇数が表示されるodds3()
はNoneType
型で,これはイテラブルでないのでエラーを吐く
>>> def odds3(): ... for num in range(1, 10, 2): ... print(num) ... >>> odds3() 1 3 5 7 9 >>> for count, number in enumerate(odds3(), 1): ... if count == 3: ... print(number) ... break ... 1 3 5 7 9 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'NoneType' object is not iterable
NoneType
とは?
>>> type(None) <class 'NoneType'>
NoneType
についてはまとめ中...