f-stringの変数化
下記のようにf-stringを用いて複数の変数を表示するのですが、同じコードを条件分岐などで複数回使います。
print(f"{month:5d} {starting:16.2f} {interest:15.2f} {principal:16.2f} {monthly_payment:7.2f} {remaining:14.2f}")
長く読みづらいので"formatted_output"として定義して再利用できないかと試してみたのですが、どのような形でprintに入れても上手くいきません。
formatted_output = f"{month:5d} {starting:16.2f} {interest:15.2f} {principal:16.2f} {monthly_payment:7.2f} {remaining:14.2f}" # 上手くいかず # print(formatted_output) # print(f"formatted_output") # print(f"{formatted_output}")
f-stringのコードを変数として定義することはできないのでしょうか?
追記
プログラムは、リボ払いでの各月の金利や支払額を表のように出力するものです。
month, startingなどはprintするごとに変化します。
# Compute a payment schedule DISCOUNT_RATE = 0.1 ANNUAL_INTEREST_RATE = 0.12 MONTHLY_INTEREST_RATE = ANNUAL_INTEREST_RATE / 12 MONTHLY_PAYMENT_RATE = 0.05 original_price = float(input("Enter the purchase price: ")) discounted_price = original_price * (1 - DISCOUNT_RATE) # The price for members month = 1 starting = discounted_price # The current total balance owed monthly_payment = ( discounted_price * MONTHLY_PAYMENT_RATE ) # the sum of interest and principal for that manth interest = discounted_price * MONTHLY_INTEREST_RATE principal = monthly_payment - interest remaining = starting - principal # The balance remaining after payment # display the titles of a table print( "\n" "Month Starting Balance Interest to Pay Principal to Pay Payment Ending Balance\n" "-----------------------------------------------------------------------------------" ) # Display the info of the first month print( f"{month:5d} {starting:16.2f} {interest:15.2f} {principal:16.2f} {monthly_payment:7.2f} {remaining:14.2f}" ) # Display the info of the second month and later while monthly_payment <= remaining: month += 1 starting = remaining interest = starting * MONTHLY_INTEREST_RATE principal = monthly_payment - interest remaining = starting - principal print( f"{month:5d} {starting:16.2f} {interest:15.2f} {principal:16.2f} {monthly_payment:7.2f} {remaining:14.2f}" ) # Evaluate the remaining and display the info of the last month if monthly_payment >= remaining: month += 1 starting = remaining interest = 0 principal = starting monthly_payment = starting remaining = 0 print( f"{month:5d} {starting:16.2f} {interest:15.2f} {principal:16.2f} {monthly_payment:7.2f} {remaining:14.2f}" )
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2019/04/18 00:48
退会済みユーザー
2019/04/18 02:55
退会済みユーザー
2019/04/18 03:41