2016-09-05 86 views
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 

回答

3

可以省略編號(它會進行自動編號你),但你仍然需要使用:結腸於所述標識符從所述格式規範分離:

print("{:<20.6f}{:<20.6f}{:<20.6f}".format(interest_rate, monthly_payment, total_payment)) 

沒有:分離器,Python的解釋一個前的內容210作爲關鍵字參數來查找(並且.6f作爲對象的屬性)。

補充說明:而不是使用eval()(打開你的腳本濫用),我會使用int()(爲整數),和float()decimal.Decimal()輸入轉換成正確的類型:

loan_amount = float(input("Enter loan amount in dollars (exclude commas):")) 
length_years = int(input("Enter the amount of years as an integer:")) 
+0

你可以告訴他'eval(input())'是壞的。在這種情況下,首選'int(input())'。 –

+0

@ Jean-FrançoisFabre:我還沒有注意那部分。我肯定會。 –

+0

當然是因爲'eval'是邪惡的(安全問題),這就是爲什麼'input'在Python 3中被更改(安全問題) –