Pythonのreturnとprint()の使い分けについて動作検証を行いました。
ある結果を出力するときにどちらを使っても良いような気がしましたが色々と試していくうちに
シーンによっては使い分けが必要となります。
今回は私のようなプログラミング初心者がreturnとprint()の使い分けができるように
いくつかのreturnとprint()のサンプルコードを実行して紹介していきます。
環境
Python | 3.9.1 |
OS | Mac(M1) Big Sur 11.1 |
returnとprint()の出力
試しにreturnとprint()で同じ数字を出力します。
def print_42():
print(42)
def return_42():
return 42
print(print_42())
print(“——————-“)
print(return_42())

結果の通りreturnでは戻り値を返していますが、print()のほうはprint()の出力結果とNoneを返しています。
print_42()のTypeを確認するとNoneTypeであることがわかります。
type(print_42())

これは関数print_42()に値がないことを意味しており、
Noneは何も返さない関数の戻り値となります。
そのためreturn_42()にprint_42()を読み込ませるとTypeErrorが発生することがわかります。
def print_42():
print(42)
def return_42():
calc = print_42() + 42
return calc
print(print_42())
print(“——————-“)
print(return_42())

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
以上のことから分かる通り、結果を表示させる目的ではなく他の関数に値を渡したい場合は
print()ではなくreturnでを利用しましょう。
def print_42():
return 42
def return_42():
calc = print_42() + 42
return calc
print(print_42())
print(“——————-“)
print(return_42())

コメント