ユーザー定義関数

Pythonの関数入門

Hugo Bowne-Anderson

Instructor

この章で学ぶこと:

  • 引数なしの関数を定義する

  • 引数1つの関数を定義する

  • 値を返す関数を定義する

  • 後ほど: 複数引数、複数の戻り値

Pythonの関数入門

組み込み関数

  • str()
x = str(5)

print(x)
'5'
print(type(x))
<class 'str'>
Pythonの関数入門

関数の定義

def square():    # <- 関数ヘッダー

new_value = 4 ** 2 # <- 関数本体 print(new_value)
square()
16
Pythonの関数入門

関数の引数

def square(value):
    new_value = value ** 2
    print(new_value)

square(4)
16
square(5)
25
Pythonの関数入門

関数の戻り値

  • return で関数から値を返す
def square(value):
    new_value = value ** 2
    return new_value

num = square(4) print(num)
16
Pythonの関数入門

Docstring

  • Docstring は関数の目的を記述します

  • 関数のドキュメントとして機能します

  • 関数ヘッダー直後の行に置きます

  • 三重の二重引用符 """ で囲みます

def square(value):
    """Returns the square of a value."""
    new_value = value ** 2
    return new_value
Pythonの関数入門

Passons à la pratique !

Pythonの関数入門

Preparing Video For Download...