Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

02 関数,モジュール・パッケージ

関数の定義と呼び出し

関数は def 関数名(): で定義し,関数名のあとに () を付けて呼び出します(call).

# 02-01. シンプルな関数
def simple_func():
    print("関数を呼び出しました.")
simple_func()
関数を呼び出しました.
# 02-02. シンプルな関数 その2
def simple_func_2():
    print("1. 関数を")
    print("2. 呼び出し")
    print("3. ました.")
simple_func_2()
1. 関数を
2. 呼び出し
3. ました.

引数

関数に値を渡すには引数 (argument)を使います.() 内に受け取りたい変数名を宣言します.

# 02-03. 引数を持つ関数
def my_abs_print(x):
    y = abs(x)
    print("入力", x)
    print("絶対値", y)
my_abs_print(5)
入力 5
絶対値 5

戻り値

return 文で値を呼び出し元に返せます.

# 02-04. 引数と戻り値をもつ関数
def add(a, b):
    c = a + b
    return c
x = add(-3.2, 4)
print(x)
0.7999999999999998

モジュールとパッケージ

モジュール (module)は関連する関数や定数をひとまとめにしたファイルです.パッケージ (package)はモジュールを階層的にまとめたものです.モジュールは import 文で読み込みます.

math モジュール

math は標準ライブラリの一つで,数学関数や定数を提供します.

# 02-05. mathモジュールの読み込み
import math
a = math.log(2)
print(a)
0.6931471805599453
# 02-07. mathモジュール
import math
print("円周率:", math.pi)
print("自然対数の底:", math.e)

print("log(2):", math.log(2))
print("√3: ", math.sqrt(3))

print("sin(π/2): ", math.sin(math.pi / 2))
print("cos(π): ", math.cos(math.pi))
print("tan(π/4): ", math.tan(math.pi / 4))
円周率: 3.141592653589793
自然対数の底: 2.718281828459045
log(2): 0.6931471805599453
√3:  1.7320508075688772
sin(π/2):  1.0
cos(π):  -1.0
tan(π/4):  0.9999999999999999

os パッケージ

os は OS(オペレーティングシステム)に関する機能を提供します.os.path.join を使うとファイルパスを OS 非依存に組み立てられます.

# 02-06. osパッケージの読み込み
import os
filepath = os.path.join("parent", "child", "file.txt")
print(filepath)
parent/child/file.txt

別名を付けた読み込み

長い名前のモジュールには,as で短い別名を付けるのが慣例です.Matplotlib の pyplot モジュールは伝統的に plt という別名で読み込みます.

# 02-08.
# matplotlibパッケージのpyplotモジュールをpltとして読み込む
import matplotlib.pyplot as plt

演習

Solution to Exercise 1
def bmi(weight, height):
    return weight / height**2


print(bmi(60, 1.70))
print(bmi(80, 1.80))
20.761245674740486
24.691358024691358
Solution to Exercise 2
import math


def circle_area(r):
    return math.pi * r**2


print(circle_area(1))
print(circle_area(2))
3.141592653589793
12.566370614359172