teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

2

c

2019/04/18 03:32

投稿

tachikoma
tachikoma

スコア3601

answer CHANGED
@@ -35,4 +35,56 @@
35
35
  "remaining": 6.0
36
36
  }
37
37
  print(s.format(**kv))
38
+ ```
39
+
40
+
41
+ ----
42
+ キーワード引数を使う場合だと、例えば一つの変数info(dictクラス)に情報を集約しておく、などですかね。
43
+
44
+ ```Python
45
+ # Compute a payment schedule
46
+
47
+ DISCOUNT_RATE = 0.1
48
+ ANNUAL_INTEREST_RATE = 0.12
49
+ MONTHLY_INTEREST_RATE = ANNUAL_INTEREST_RATE / 12
50
+ MONTHLY_PAYMENT_RATE = 0.05
51
+
52
+ original_price = float(input("Enter the purchase price: "))
53
+ discounted_price = original_price * \
54
+ (1 - DISCOUNT_RATE) # The price for members
55
+
56
+ info = {
57
+ "month": 1,
58
+ "starting": discounted_price, # The current total balance owed
59
+ # the sum of interest and principal for that manth
60
+ "monthly_payment": discounted_price * MONTHLY_PAYMENT_RATE,
61
+ "interest": discounted_price * MONTHLY_INTEREST_RATE,
62
+ }
63
+ info["principal"] = info["monthly_payment"] - info["interest"]
64
+ # The balance remaining after payment
65
+ info["remaining"] = info["starting"] - info["principal"]
66
+
67
+ # display the titles of a table
68
+ print(
69
+ "\n"
70
+ "Month Starting Balance Interest to Pay Principal to Pay Payment Ending Balance\n"
71
+ "-----------------------------------------------------------------------------------"
72
+ )
73
+
74
+
75
+ # Display the info of the first month
76
+ s = "{month:5d} {starting:16.2f} {interest:15.2f} {principal:16.2f} {monthly_payment:7.2f} {remaining:14.2f}"
77
+ print(s.format(**info))
78
+
79
+
80
+ # Display the info of the second month and later
81
+ while info["monthly_payment"] <= info["remaining"]:
82
+ info["month"] += 1
83
+ info["starting"] = info["remaining"]
84
+ info["interest"] = info["starting"] * MONTHLY_INTEREST_RATE
85
+ info["principal"] = info["monthly_payment"] - info["interest"]
86
+ info["remaining"] = info["starting"] - info["principal"]
87
+
88
+ print(s.format(**info))
89
+
38
90
  ```

1

..

2019/04/18 03:32

投稿

tachikoma
tachikoma

スコア3601

answer CHANGED
@@ -5,4 +5,34 @@
5
5
  print(s.format(month=...))
6
6
  ```
7
7
 
8
- というように、テンプレートとしての文字列sを一個作って、あとから必要な場所で.formatメソッドを呼ぶ形にすればテンプレートsを使いまわすことができます。
8
+ というように、テンプレートとしての文字列sを一個作って、あとから必要な場所で.formatメソッドを呼ぶ形にすればテンプレートsを使いまわすことができます。
9
+
10
+ ----
11
+ 追記
12
+
13
+ print部分を短くするだけなら次のような方法があります。
14
+
15
+ 位置引数を使う場合。
16
+
17
+ ```Python
18
+ s = "{:5d} {:16.2f} {:15.2f} {:16.2f} {:7.2f} {:14.2f}"
19
+
20
+ values = [1, 2.0, 3.0, 4.0, 5.0, 6.0]
21
+ print(s.format(*values))
22
+ ```
23
+
24
+ キーワード引数を利用する場合。
25
+
26
+ ```Python
27
+ s = "{month:5d} {starting:16.2f} {interest:15.2f} {principal:16.2f} {monthly_payment:7.2f} {remaining:14.2f}"
28
+
29
+ kv = {
30
+ "month": 1,
31
+ "starting": 2.0,
32
+ "interest": 3.0,
33
+ "principal": 4.0,
34
+ "monthly_payment": 5.0,
35
+ "remaining": 6.0
36
+ }
37
+ print(s.format(**kv))
38
+ ```