読み方のヒント

矢印ボタン(または ← → キー)でページを移動できます。

第5節 処理の分割と仮想環境

5.1 処理をファイルに分ける

ここまでの関数を、役割ごとに2つのファイルに分けます。

python-renshu
├── quantity.py
├── main.py
└── reservation.json

quantity.py には、合計個数と上限の判定をする関数を書きます。

def total_quantity(items: list[dict]) -> int:
    total = 0
    for item in items:
        total = total + item["quantity"]
    return total


def is_within_limit(items: list[dict]) -> bool:
    return total_quantity(items) <= 10

main.py には、ファイルを読み、関数を呼び、結果を表示する処理を書きます。

import json

from quantity import is_within_limit, total_quantity

with open("reservation.json", encoding="utf-8") as f:
    reservation = json.load(f)

count = total_quantity(reservation["items"])
if is_within_limit(reservation["items"]):
    print(f"{reservation['name']}さん:合計{count}個で受け付けます")
else:
    print(f"{reservation['name']}さん:合計{count}個は上限を超えています")
田中さん:合計3個で受け付けます

quantity.py は計算だけ、main.py は入力と表示だけを受け持ちます。計算の決まりが変わったときは quantity.py だけを直せばよく、どこを読めばよいかがすぐ分かります。

f文字列の中で辞書のキーを書くときは、外側の " と区別するために、キーを ' で囲みます。

18 / 20