Python 3.5.1格式化浮动问题

时间:2016-09-05 20:26:10

标签: python floating-point python-3.5

我正在尝试创建一个应用程序,将各种利率的贷款与编程任务进行比较。我通常理解我在做什么,可以完成任务,但遇到了.format函数的问题。我正在尝试格式化浮点数,以便可以将它们打印为结果。这是我的代码:

# 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

1 个答案:

答案 0 :(得分:3)

您可以省略编号(并且它会自动为您编号),但您仍需要使用:冒号将标识符与格式规范分开:

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

如果没有:分隔符,Python会将.之前的内容解释为要查找的关键字参数(并.6f作为对象的属性)。

作为旁注:不要使用eval()(并打开您的脚本进行滥用),我会使用int()(对于整数),float()或{ {1}}将输入转换为正确的类型:

decimal.Decimal()