LoginSignup
1
0

[Python] 自作関数の定義パタンと用語整理

Last updated at Posted at 2022-12-14

目的

  • Python勉強ノート
  • パタン整理
  • 用語まとめ

関数の定義方法

my_function
def my_function():
    #実行する内容1
    #実行する内容2

実行方法

my_function():

パタン① パラメータに引数与えて関数の内容を実行する

実行してみよう

2つの引数("anna", "good")をパラメータに与えて中の決まった処理をするコードを書いて実行してみよう。

hello.py
def hello(name, weather):
    print(f"Hello {name}, The weather is {weather}.")
    print("Isn't it? Bye")

hello("anna", "good")  
実行結果
Hello anna, The weather is good.
Isn't it? Bye

パラメータ(Parameter)と引数(Argument)の関係

実行結果で関数(hello)に渡されるParameterとArgumentについて

  • name/weather = Parameter 値の名前(パラメータ)
  • anna/good = Argument 実際の値 (引数, Data/Value)

補足 「Positional Arguments」と「Keyword Arguments」の違いと使い分け

今回は"good", "anna"の順番逆にして与えると?

hello.py
def hello(name, weather):
    print(f"Hello {name}, The weather is {weather}.")
    print("Isn't it? Bye")

hello("good", "anna")

こんなバカげた結果を招く、つまり・・・
Pythonは「名前」「good or bad」の見分けをしないということ

実行結果
Hello good, The weather is anna.
Isn't it? Bye

簡単なコードは気を付けて入力し、結果をテストすることで
「Positional Arguments」を使うことで問題ないと思う。

それに比べて「Keyword Arguments」は

hello.py
def hello(name, weather):
    print(f"Hello {name}, The weather is {weather}.")
    print("Isn't it? Bye")

hello(weather = "good", name = "anna")

キーに値を直接指定することで意図した結果が得られるので、エラーを減らせるだろう。ただ、めんどくさいかも・・・

実行結果
Hello good, The weather is anna.
Isn't it? Bye

パタン② 関数が処理した実行結果を呼び出し元へ返す(return)

パタン①ではただ、画面に挨拶を表示するに比べて
「return」を利用すると呼び出し元へ値を返すことができる。
例えば

total.py (「a」に「b」を足した結果を返す関数)
def add(a, b):
    return a + b

「total」という変数を作ってそのに「add」のリターンされた処理結果を代入し、「total」を出力する。

実行
total = add(1, 3)
print(total)
4 # 結果2つの引数の合計が表示されることが確認できる。

任意の変数に代入した戻り値は何度でも利用できたり、別の関数で使えるので
「表示」だけではなく、「再利用」するのであれば「return」を使うべし。

「return」と「print」を両方設ける関数では順番に気を付けよう。

例えばこのように両方使う場合、どうなるのか考えてみよう。

def add(a, b):
    return a + b
    print("この関数は「a」に「b」を足した結果を返す関数です。")

total = add(1, 3)
print(total)
returnをprintより先に書く場合の結果
4

「return」が実行されて関数の処理は終了されるので「print」を先に実行する必要がある。

修正後
    print("この関数は「a」に「b」を足した結果を返す関数です。")
    return a + b
printをreturnより先に書く場合の結果
この関数は「a」に「b」を足した結果を返す関数です。
4

これ以外にも勉強する中でよく使うなと思うパタンがあると追記する予定

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