入力と出力の応用テクニック
これまで学んだ print() と input() を組み合わせて、より実践的なプログラムを作るテクニックを学びましょう。
1. 出力の整形:f文字列 + 書式指定
f文字列の {変数:.nf} で小数点以下の桁数を指定できます。
price = 1234.567
print(f"金額(端数なし):{price:.0f}円")
print(f"金額(1桁) :{price:.1f}円")
print(f"金額(2桁) :{price:.2f}円")
print(f"割合 :{0.856:.1%}")
▶ 出力結果
金額(端数なし):1235円 金額(1桁) :1234.6円 金額(2桁) :1234.57円 割合 :85.6%
2. 区切り線で出力を読みやすく整える
name = input("商品名:")
price = float(input("価格(円):"))
qty = int(input("個数:"))
total = price * qty
tax = total * 0.1
print("=" * 30)
print(f" 商品名:{name}")
print(f" 単価 :{price:.0f}円")
print(f" 個数 :{qty}個")
print("-" * 30)
print(f" 小計 :{total:.0f}円")
print(f" 消費税:{tax:.0f}円")
print("=" * 30)
print(f" 合計 :{total + tax:.0f}円")
▶ 実行の流れ(りんご・150円・3個を入力した場合)
商品名:りんご 価格(円):150 個数:3 ============================== 商品名:りんご 単価 :150円 個数 :3個 ------------------------------ 小計 :450円 消費税:45円 ============================== 合計 :495円
3. 入力値の確認(echo back)
受け取った値をユーザーに見せて確認させるのは、フォームアプリの基本パターンです。
email = input("メールアドレス:")
confirm = input(f"{email} で登録しますか?(yes/no):")
print(f"回答:{confirm}")
▶ 実行の流れ
メールアドレス:test@example.com test@example.com で登録しますか?(yes/no):yes 回答:yes
