1
0

Functions - CS50’s Introduction to Programming with Python

Last updated at Posted at 2024-03-03

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

まだ下記の記事を読んでいない方は、先にこちらを読んでからの方がわかりやすいかもしれません。
VSCodeのTerminalの使い方とCommand LineをHavard CS50の動画で学ぶ

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

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

Pythonファイルの作成

Terminalで

Terminal
code hello.py

実行して、ファイルを作成します。

functionとargumentを書く

今度は、今作成したhello.pyのファイルに

hello.py
print("Hello, world!")
print("This is CS50P.")

と入力します。
functionは、function名と()よりできています。
上記だとprintがfunction名です。()の中には、argumentを記入します。上記だと"Hello, world!"と”This is CS50P."がargumentです。

Pythonファイルを実行する

Terminal
python hello.py

を実行するとpythonファイルが実行されます。

functionを定義する(define)

defを使うとオリジナルのfunctionを作ることができます。

hello.py
def main():
    print("Hello, world!")
    print("This is CS50P.")

とするとmainというfunctionができます。
ここで、

Terminal
python hello.py

を実行してもなにも出力されません。
functionを定義しただけだと出力されないので呼び出す必要があります。

functionを呼び出す(call)

hello.py
def main():
    print("Hello, world!")
    print("This is CS50P.")

main()

main()とかいて呼び出します(call)
ここで、

Terminal
python hello.py

を実行すると、今度は、正常に出力されます。

次に読むのにオススメの記事
Return Values - CS50’s Introduction to Programming with Python

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