LoginSignup
7
10

More than 5 years have passed since last update.

Python 3: print と return について(超基礎)

Last updated at Posted at 2018-02-14

print()returnについて

関数の定義でprint()returnどちらをつかうべきか?

  • print()・・・表示するだけ
  • return・・・戻り値を返す
print()で表示するだけの関数を実行した
>>> def print_hello():
...     print("hello")
...
>>> print_hello()
hello
returnで返ってきた"hello"という文字列をprint()で表示した
>>> def return_hello():
... return "hello"
...
>>> return_hello()
'hello'
>>> print(return_hello())
hello

ジェネレータ関数で理解を深める

  • ジェネレータ関数では,returnの代わりにyieldを用いる
  • ジェネレータ関数を定義して,イテレータのように値を次々を取り出せるオブジェクトを作ることができる

Questionrange(10)から奇数を返すoddsというジェネレータ関数を定義し,返された3番目の値を見つけて表示せよ.


  • odds()を実行するとジェネレータ・オブジェクトであることが分かる.
yieldを用いた場合
>>> 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型であることが分かる
returnを用いた場合
>>> 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型で,これはイテラブルでないのでエラーを吐く
printを用いた場合
>>> 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とは?

Noneの型はNoneTypeである
>>> type(None)
<class 'NoneType'>

NoneTypeについてはまとめ中...

7
10
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
10