データを読み込み中...

この教材では、プログラムを「部品」として整理する方法である「関数」について学びます。関数を使うことで、コードの再利用性が高まり、プログラムが読みやすく、保守しやすくなります。
これまで学んできたプログラムでは、同じような処理を何度も書く必要がありました。
例えば、消費税込みの価格を計算する場面を考えてみましょう
# 商品Aの税込価格
price_a = 1000
tax_a = price_a * 0.1
total_a = price_a + tax_a
print("商品A: {}円".format(total_a))
# 商品Bの税込価格
price_b = 1500
tax_b = price_b * 0.1
total_b = price_b + tax_b
print("商品B: {}円".format(total_b))
# 商品Cの税込価格
price_c = 800
tax_c = price_c * 0.1
total_c = price_c + tax_c
print("商品C: {}円".format(total_c))
同じ計算を3回繰り返しています。これでは
関数を使えば、この繰り返しをなくせます
def calculate_with_tax(price):
"""税込価格を計算する"""
tax = price * 0.1
total = price + tax
return total
# 関数を使って計算
print("商品A: {}円".format(calculate_with_tax(1000)))
print("商品B: {}円".format(calculate_with_tax(1500)))
print("商品C: {}円".format(calculate_with_tax(800)))
関数にすることで
関数とは、特定の処理をまとめて名前をつけたものです。
日常生活で例えると
プログラムでも同じです
これまでもprint()、len()、sum()などの関数を使ってきました。これらは Pythonに最初から用意されている関数(組み込み関数)です。今回学ぶのは、自分で関数を作る方法です。
関数を定義するにはdef文を使います
def 関数名():
# 実行したい処理
処理1
処理2
実際に簡単な関数を作ってみましょう
def greet():
"""挨拶をする関数"""
print("こんにちは!")
print("今日も良い一日を!")
# 関数を呼び出す
greet()
実行結果
こんにちは!
今日も良い一日を!
関数定義のポイント
defの後に関数名を書く()をつける:(コロン)をつける()をつけて呼び出す関数名は変数名と同じルールに従います
# 良い関数名の例
def calculate_total():
pass
def show_menu():
pass
def get_user_name():
pass
# 推奨されない関数名
def f(): # 何をする関数かわからない
pass
def MyFunction(): # Pythonでは小文字+アンダースコアが推奨
pass
関数名は「何をする関数か」がわかるように、動詞で始めることが多いです
calculate_ : 計算するshow_ : 表示するget_ : 取得するcheck_ : 確認する関数に情報を渡したい場合、引数を使います。
def greet(name):
"""名前を受け取って挨拶する"""
print("こんにちは、{}さん!".format(name))
# 関数を呼び出すときに値を渡す
greet("田中") # こんにちは、田中さん!
greet("佐藤") # こんにちは、佐藤さん!
この例では:
nameが仮引数(関数定義時のパラメータ)"田中"や"佐藤"が実引数(関数呼び出し時に渡す値)引数は複数指定できます
def calculate_area(width, height):
"""長方形の面積を計算する"""
area = width * height
print("幅{}cm × 高さ{}cm = 面積{}cm²".format(width, height, area))
calculate_area(5, 10) # 幅5cm × 高さ10cm = 面積50cm²
calculate_area(8, 12) # 幅8cm × 高さ12cm = 面積96cm²
関数の実行結果を呼び出し元に返すには、return文を使います
def add(a, b):
"""2つの数値を足し算する"""
result = a + b
return result
# 関数の戻り値を変数に格納
total = add(10, 20)
print(total) # 30
# 戻り値を直接使うこともできる
print(add(5, 8)) # 13
returnのポイント
returnの後に返したい値を書くreturnが実行されると、関数はその時点で終了するreturnがない関数は、暗黙的にNoneを返すdef multiply(a, b):
"""2つの数値を掛け算する"""
return a * b
# 戻り値を使って別の計算ができる
result1 = multiply(3, 4) # 12
result2 = multiply(5, 6) # 30
final_result = result1 + result2
print(final_result) # 42
def calculate_bmi(weight, height):
"""BMIを計算する
weight: 体重(kg)
height: 身長(cm)
戻り値: BMI値
"""
# 身長をメートルに変換
height_m = height / 100
# BMIを計算
bmi = weight / (height_m ** 2)
return bmi
def judge_bmi(bmi):
"""BMI値を判定する
bmi: BMI値
戻り値: 判定結果(文字列)
"""
if bmi < 18.5:
return "低体重"
elif bmi < 25:
return "普通体重"
elif bmi < 30:
return "肥満(1度)"
else:
return "肥満(2度以上)"
# 関数を組み合わせて使う
weight = 68
height = 170
bmi_value = calculate_bmi(weight, height)
result = judge_bmi(bmi_value)
print("BMI: ".format(bmi_value))
print("判定: {}".format(result))
このように、関数を組み合わせることで、複雑な処理を整理できます。
一度作った関数は、何度でも使えます
def format_price(price):
"""価格を見やすく表示する"""
return "円".format(price)
# 様々な場面で再利用
print("商品A: {}".format(format_price(1500)))
print("商品B: {}".format(format_price(98000)))
print("合計: {}".format(format_price(123456)))
処理を変更したいとき、関数なら1箇所を修正するだけで済みます。
# 税率8%の関数
def calculate_with_tax(price):
"""税込価格を計算する"""
tax_rate = 0.08 # ここを変更すれば、すべての計算が変わる
return int(price * (1 + tax_rate))
print(calculate_with_tax(1000)) # 1080
print(calculate_with_tax(1500)) # 1620
# 税率を10%に変更したい場合、
# tax_rate = 0.10 に変更するだけ
処理に名前がつくことで、コードが読みやすくなります。
# 関数なしの場合(何をしているかわかりにくい)
score = 85
if score >= 80:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "D"
# 関数ありの場合(意図が明確)
def get_grade(score):
"""点数から成績を判定する"""
if score >= 80:
return "A"
elif score >= 70:
return "B"
elif score >= 60:
return "C"
else:
return "D"
grade = get_grade(85) # 「成績を取得している」とわかる
引数にデフォルト値を設定すると、その引数を省略できるようになります。
def greet(name, greeting="こんにちは"):
"""挨拶をする
name: 名前
greeting: 挨拶の言葉(省略可能、デフォルトは"こんにちは")
"""
print("{}、{}さん!".format(greeting, name))
# 通常の呼び出し
greet("田中", "おはよう") # おはよう、田中さん!
# デフォルト値を使う(greetingを省略)
greet("佐藤") # こんにちは、佐藤さん!
def search_product(keyword, max_results=10):
"""商品を検索する
keyword: 検索キーワード
max_results: 最大表示件数(デフォルトは10件)
"""
print("「{}」で検索中...".format(keyword))
print("最大{}件表示します".format(max_results))
# デフォルトの10件表示
search_product("ノートPC")
# 表示件数を指定
search_product("スマートフォン", 5)
デフォルト値がある引数は、ない引数の後に書く必要があります。
# 正しい例
def create_user(name, age, role="一般"):
pass
# 間違った例(エラーになる)
# def create_user(name, role="一般", age):
# pass
def calculate_statistics(numbers):
"""数値リストの統計情報を計算する
numbers: 数値のリスト
戻り値: 辞書(合計、平均、最大、最小)
"""
if len(numbers) == 0:
return None
total = sum(numbers)
average = total / len(numbers)
maximum = max(numbers)
minimum = min(numbers)
return {
"合計": total,
"平均": average,
"最大": maximum,
"最小": minimum
}
# テストの点数で使用
scores = [85, 92, 78, 88, 95, 73, 90]
stats = calculate_statistics(scores)
print("=== 統計情報 ===")
for key, value in stats.items():
if key == "平均":
print("{}: ".format(key, value))
else:
print("{}: {}".format(key, value))
def add_stock(inventory, product_code, quantity):
"""在庫を追加する
inventory: 在庫辞書
product_code: 商品コード
quantity: 追加数量
"""
if product_code in inventory:
inventory[product_code] += quantity
else:
inventory[product_code] = quantity
print("商品{}: {}個追加しました".format(product_code, quantity))
def check_stock(inventory, product_code):
"""在庫を確認する
inventory: 在庫辞書
product_code: 商品コード
戻り値: 在庫数(存在しない場合は0)
"""
return inventory.get(product_code, 0)
# 在庫管理システム
warehouse = {}
add_stock(warehouse, "A001", 50)
add_stock(warehouse, "B002", 30)
add_stock(warehouse, "A001", 20) # 追加
print("\n現在の在庫:")
for code, stock in warehouse.items():
print("{}: {}個".format(code, stock))
print("\n商品A001の在庫: {}個".format(check_stock(warehouse, "A001")))
def find_max_score_student(scores):
"""最高点の生徒を見つける
scores: 成績辞書(名前: 点数)
戻り値: (名前, 点数)のタプル
"""
max_name = ""
max_score = -1
for name, score in scores.items():
if score > max_score:
max_score = score
max_name = name
return (max_name, max_score)
def count_passed(scores, passing_score=60):
"""合格者数をカウントする
scores: 成績辞書
passing_score: 合格点
戻り値: 合格者数
"""
count = 0
for score in scores.values():
if score >= passing_score:
count += 1
return count
# テストデータ
test_scores = {
"田中": 85,
"佐藤": 92,
"鈴木": 78,
"高橋": 65,
"伊藤": 58
}
# 最高点の生徒
top_student, top_score = find_max_score_student(test_scores)
print("最高点: {} ({}点)".format(top_student, top_score))
# 合格者数
passed = count_passed(test_scores)
print("合格者: {}人".format(passed))
以下の要件を満たすプログラムを作成してください。
要件
check_even_odd()を作成する期待する出力例
10は偶数です
7は奇数です
24は偶数です
33は奇数です
ヒント
n % 2 == 0で偶数判定以下の要件を満たすプログラムを作成してください。
要件
calculate_subtotal()を作成する期待する出力例
小計: 3600円
割引後: 3600円
小計: 6000円
割引後: 5400円
小計: 4000円
割引後: 4000円
ヒント
以下の要件を満たすプログラムを作成してください。
要件
filter_passing_scores()を作成するadd_bonus_points()を作成するscores = [55, 72, 68, 45, 88, 91, 58, 76]
期待する出力例
元の点数: [55, 72, 68, 45, 88, 91, 58, 76]
合格点: [72, 68, 88, 91, 76]
ボーナス加算後: [65, 82, 78, 55, 98, 101, 68, 86]
ヒント
以下の要件を満たすプログラムを作成してください。
要件
以下の関数を作成する
create_user(user_id, name, age): ユーザー情報を辞書で返すis_adult(user): ユーザー辞書を受け取り、20歳以上ならTrueを返すshow_user_info(user): ユーザー情報をわかりやすく表示する以下のユーザーを作成し、情報を表示する
各ユーザーについて、成人かどうかも表示する
期待する出力例
=== ユーザー情報 ===
ID: U001
名前: 田中太郎
年齢: 25歳
成人: はい
ID: U002
名前: 佐藤花子
年齢: 18歳
成人: いいえ
ID: U003
名前: 鈴木一郎
年齢: 30歳
成人: はい
ヒント
{"id": user_id, "name": name, "age": age}user["age"] >= 20 で判定この教材では、以下の内容を学習しました
def 関数名():で定義するこれで、Python の基礎文法(変数、演算子、条件分岐、ループ、リスト、辞書、関数)をすべて学習しました。これらを組み合わせることで、実用的なプログラムを作ることができます。演習問題をしっかり解いて、関数の使い方をマスターしましょう。