1
我正在嘗試創建一個應用程序,它將貸款與各種利率進行比較,以進行編程分配。我通常明白我在做什麼,可以完成任務,但遇到了.format函數的問題。我試圖格式化浮動,以便它們可以作爲結果打印。這裏是我的代碼:Python 3.5.1格式化浮動問題
# Prompts the user to enter a loan amount
loan_amount = eval(input("Enter loan amount in dollars (exclude commas):"))
# Prompts the user to enter a time period
length_years = eval(input("Enter the amount of years as an integer:"))
# Displays the header
print("{0:20s}{1:20s}{2:20s}".format("Interest Rate", "Monthly Payment",
"Total Payment"))
interest_rate = 5.0
while (interest_rate <= 8.0):
monthly_interest_rate = interest_rate/12
monthly_payment = (monthly_interest_rate/100) * loan_amount
total_payment = ((interest_rate/100) * length_years) * loan_amount
print("{<20.6f}{<20.6f}{<20.6f}".format(interest_rate, monthly_payment, total_payment))
interest_rate = interest_rate +.25
這是錯誤我收到:
Enter loan amount in dollars (exclude commas):1000
Enter the amount of years as an integer:10
Traceback (most recent call last):
Interest Rate Monthly Payment Total Payment
File "/Users/Andrew/PycharmProjects/PA1/pa1_main.py", line 45, in <module>
main()
File "/Users/Andrew/PycharmProjects/PA1/pa1_main.py", line 42, in main
print("{<20.6f}{<20.6f}{<20.6f}".format(interest_rate, monthly_payment, total_payment))
KeyError: '<20'
Process finished with exit code 1
你可以告訴他'eval(input())'是壞的。在這種情況下,首選'int(input())'。 –
@ Jean-FrançoisFabre:我還沒有注意那部分。我肯定會。 –
當然是因爲'eval'是邪惡的(安全問題),這就是爲什麼'input'在Python 3中被更改(安全問題) –