初級演習:お買い物計算機
変数・演算・if文・f文字列を組み合わせて、消費税計算と割引処理ができる「お買い物計算機」を作ります。
📝 問題
以下の仕様を満たすプログラムを作成してください。
- 商品のリスト(名前と価格のペア)を定義する
- 全商品の合計(税抜)を計算する
- 消費税 10% を加算して税込合計を求める
- 税込合計が 3000円以上 なら 5%割引 を適用する
- 以下の形式で領収書を出力する
商品名 金額
================================
りんご 200円
パン 350円
...
--------------------------------
小計 xxxx円
消費税(10%) xxxx円
割引(-5%) -xxxx円 ← 該当する場合のみ表示
================================
合計 xxxx円
💡 ヒント
- 商品リストは
[("りんご", 200), ("パン", 350), ...]のようにタプルのリストで定義できます - 合計は
sum(price for _, price in items)または for ループで計算できます - 文字列のフォーマットは
f"{name:<10} {price:>6}円"のように指定できます - 割引は
if total >= 3000:で分岐します
✅ 回答例
items = [
("りんご", 200),
("パン", 350),
("牛乳", 180),
("チーズ", 1200),
("ジュース", 250),
]
TAX_RATE = 0.10
DISCOUNT_RATE = 0.05
DISCOUNT_MIN = 3000
# 合計計算
subtotal = sum(price for _, price in items)
tax = int(subtotal * TAX_RATE)
total_before_discount = subtotal + tax
# 割引判定
if total_before_discount >= DISCOUNT_MIN:
discount = int(total_before_discount * DISCOUNT_RATE)
total = total_before_discount - discount
else:
discount = 0
total = total_before_discount
# 領収書出力
print("=" * 32)
print(f"{'商品名':<10}{'金額':>8}")
print("=" * 32)
for name, price in items:
print(f"{name:<12} {price:>6}円")
print("-" * 32)
print(f"{'小計':<12} {subtotal:>6}円")
print(f"{'消費税(10%)':<12} {tax:>6}円")
if discount > 0:
print(f"{'割引(-5%)':<12}-{discount:>5}円")
print("=" * 32)
print(f"{'合計':<12} {total:>6}円")
print("=" * 32)
▶ 出力結果
================================ 商品名 金額 ================================ りんご 200円 パン 350円 牛乳 180円 チーズ 1200円 ジュース 250円 -------------------------------- 小計 2180円 消費税(10%) 218円 割引(-5%) -119円 ================================ 合計 2279円 ================================
🔍 解説ポイント
int()で小数点以下を切り捨て(税額・割引額の端数処理)f"{name:<12}"は左寄せ12文字幅、f"{price:>6}"は右寄せ6文字幅if discount > 0:で割引がある場合のみ割引行を表示
