1
0

Return Values - CS50’s Introduction to Programming with Python

Last updated at Posted at 2024-03-03

CS50’s Introduction to Programming with PythonのShortsよりReturn Valuesの内容を記載したいと思います。動画で勉強しながら、復習になど使っていただけたら嬉しいです。

まだ、下記の記事を読んでいない方は、先にそちらを読んだ方が、わかりやすいと思います。
Functions - CS50’s Introduction to Programming with Python

動画へは下記リンクよりアクセスできます。動画を見ながらまたは、復習として、この記事をご活用ください。
Return Values - CS50P Shorts

まず、Visual Studio Code for CS50にアクセスして、GitHubアカウントでログインします。

Terminalで

Terminal
code greeting.py

を実行して、greeting.pyのファイルを作成します。

greet functionを定義します。

greeting.py
def greet(input):
	if "hello" in input:
		print("hello, there")
	else:
		print("I'm not sure what you mean")

定義したgreet functionを呼び出します。今回は、argumentも入力します。入力しがargumentは、inputにわたされて、functionが実行されます。argumentに"hello"が含まれていれば、"hello, there"と、そうでなければ"I'm not sure what you mean"と返されます。

greeting.py
def greet(input):
	if "hello" in input:
		print("hello, there")
	else:
		print("I'm not sure what you mean")
greet("hello, computer")
Terminal
python greeting.py

を実行すると
"hello, there"と返ってきます。

今度は、returnされるようにします。
先ほどのコードのprint functionをreturnに変更します。

greeting.py
def greet(input):
	if "hello" in input:
		return "hello, there"
	else:
		return "I'm not sure what you mean"

greet("hello, computer")

ここで、先ほどのように
greeting.pyを実行してもなにも返ってきません。returnで返されたものは、どこかに保存してそれをprintしないと実際に返ってきたものを見ることはできません。

greeting.py
def greet(input):
	if "hello" in input:
		return "hello, there"
	else:
		return "I'm not sure what you mean"

greeting = greet("hello, computer")
print(greeting)

greetingにgteet functionに返ってきた値を代入して、print functionで書き出します。

今度は、python greeting.pyを実行するとhello, thereと出力されます。
print(greeting)をprint("Hm, " + greeting)やprint(greeting + " Carter")に変更して実行してみます。

returnを使うとside effectとしてすぐに何かが出力されるのではなく、他のところで、再利用したり、値を渡したりすることができます。

1
0
0

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
1
0