デフォルト引数と可変長引数

Pythonの関数入門

Hugo Bowne-Anderson

Instructor

学習内容:

  • デフォルト引数付きの関数を作成

  • 可変長引数を使用

    • 任意個の引数を関数に渡す
Pythonの関数入門

デフォルト引数を追加

def power(number, pow=1):
   """number を pow 乗する。"""
   new_value = number ** pow
   return new_value

power(9, 2)
81
power(9, 1)
9
power(9)
9
Pythonの関数入門

可変長引数: *args (1)

def add_all(*args):
    """*args の値をすべて合計する。"""

    # 合計を初期化
    sum_all = 0

    # 合計を加算
    for num in args:
        sum_all += num

    return sum_all
Pythonの関数入門

可変長引数: *args (2)

add_all(1)
1
add_all(1, 2)
3
add_all(5, 10, 15, 20)
50
Pythonの関数入門

可変長引数: **kwargs

print_all(name="Hugo Bowne-Anderson", employer="DataCamp")
name: Hugo Bowne-Anderson
employer: DataCamp
Pythonの関数入門

可変長引数: **kwargs

def print_all(**kwargs):
    """**kwargs のキーと値を出力する。"""

    # キーと値を出力
    for key, value in kwargs.items():
        print(key + ": " + value)
print_all(name="dumbledore", job="headmaster")
job: headmaster
name: dumbledore
Pythonの関数入門

Passons à la pratique !

Pythonの関数入門

Preparing Video For Download...