AndrewSikorski AndrewSikorski - 6 months ago 33
Python Question

Python 3.5.1 Formatting Floats Issue

I am trying to create a app that compares loans with various interest rates for a programming assignment. I generally understand what I am doing and could complete the assignment but am running into an issue with the .format function. I'm trying to format floats so that they can be printed as results. Here is my code:

# 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

And this is the error I receive:

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/", line 45, in <module>
File "/Users/Andrew/PycharmProjects/PA1/", 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


You can omit the numbering (and it'll be auto-numbered for you), but you still need to use the : colon to separate the identifier from the formatting specification:

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

Without the : separator, Python interprets the content before a . as a keyword argument to look up (and .6f as an attribute on the object).

As a side note: rather than use eval() (and open your script to abuse), I'd use int() (for whole numbers), and float() or decimal.Decimal() to convert input into the correct type:

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