Reputation: 93
So I am trying to insert a percentage sign at the end of my output for the variable rate. However I am getting a "TypeError: unsupported operand type(s) for +: 'float' and 'str'" error." How do I format the output so that I could put a '%' sign on it.
Loan = eval(input("Enter loan amount, for example 120000: "))
while Loan <= 12000 or Loan >= 125000:
print("Please enter a value more than 120000 or less than 125000")
Loan = eval(input("Enter loan amount, for example 120000: "))
Year = eval(input("Enter number of years as an integer, for example 7: "))
while Year < 5 or Year >10:
print("Please enter a number more than 5 or less than 10")
Year = eval(input("Enter number of years as an integer, for example 7: "))
print('%-20s%-20s%-20s' % ('Interest Rate', 'Monthly Payment', 'Total Payment'))
Rate = 5.0
while Rate <= 8:
adjRate = Rate / 1200
monthlyPayment = Loan * adjRate / (1 - 1 / (1 + adjRate) ** (Year * 12))
totalPayment = monthlyPayment * Year * 12
print('%-20.3f%-20.2f%-20.2f' % (Rate, monthlyPayment, totalPayment))
Rate += 0.125
I tried:
print('%-20.3f%-20.2f%-20.2f' % (Rate+'%', monthlyPayment, totalPayment))
but got an
TypeError: unsupported operand type(s) for +: 'float' and 'str'"
Upvotes: 0
Views: 741
Reputation: 88478
Since Rate
is a float and '%'
is a str, the expression
Rate + '%'
is indeed illegal: in Python, you cannot "add" a float and a str.
So that's the cause of the specific error you inquired about. To fix it, you can do the following:
print('%20.3f%s%20.2f%20.2f' % (Rate, '%', monthlyPayment, totalPayment))
So that the %s
in the format string gets you the %
.
I also removed the negative signs, as numbers should generally be right aligned.
If you are using Python 3.6 or above I highly recommend writing this as:
print(f'{Rate:20.3f}%{monthlyPayment:20.2f}{totalPayment:20.2f'})
Again, this just answers the reason for your error. The use of eval
is actually another matter; it should not be used the way you used it here. (Just pointing that out since I feel an obligation to do so.)
Upvotes: 2
Reputation: 511
Never use eval on user input, use input and validate what is entered; otherwise this opens up so many security holes.
Instead use conversion commands like float()
and int()
.
So, for example:
loan_str = input("Enter loan amount")
loan_amt = int(loan_amt)
Wrap everything in try/except to catch people putting in "fifty thousand" instead of "50000"
This will also ensure that your values are the correct type for your code.
To embed a '%' in your string use '%%'
Upvotes: 2