Hi all, i am trying to write a mortgage amortization schedule calculator and am stuck. please see the code below. It appears that the principal is being counted twice before subtracting it from the balance. Any ideas on what the issue is? I am new to python:

``````loanAmount = input("Please enter the loan amount: ")
iR = input("Please enter the interest rate: ")
iR = float(iR)
term = input("Please enter the term: ")
monthlyRate = iR/(12 * 100)
loanTerm = term*12
monthlyPayment = loanAmount * (monthlyRate/(1 - (1 + monthlyRate)** -loanTerm))
monthlyPayment = float(monthlyPayment)
monthlyPayment = round(monthlyPayment, 2)
interest = loanAmount*monthlyRate
balance = loanAmount - monthlyRate

print "PmtNo\t\tInterest\tPrincipal\tBalance"

for i in range (1, loanTerm + 1):
pi = balance*monthlyRate
monthlyPayment = loanAmount * (monthlyRate/(1 - (1 + monthlyRate)** -loanTerm))
prepay= monthlyPayment - pi
balance = loanAmount - prepay
remaining_balance = balance - prepay
if balance < 0:
pi = balance*monthlyRate
balance = loanAmount - prepay
prepay = monthlyPayment - pi
remaining_balance = balance - prepay
print "%d\t\t%0.2f\t\t%0.2f\t\t%0.2f" % (i, pi, prepay, 0)
break
print "%d\t\t%0.2f\t\t%0.2f\t\t%0.2f" % (i, pi, prepay, remaining_balance)
``````

I would suggest that you first write it out on paper with 2 or 3 actual examples of what you want and then see how the program differs from the actual examples. For example, balance and remaining balance never change, why? How would you keep track of remaining balance when …

May I suggest that you group things together in functions to get a better view and clarity...

data_input
processing the data (calculation)
data_output

Give your functions and arguments/variables meaningful names to help readability.

## All 4 Replies

I would suggest that you first write it out on paper with 2 or 3 actual examples of what you want and then see how the program differs from the actual examples. For example, balance and remaining balance never change, why? How would you keep track of remaining balance when doing it by hand?

Line 7 is needlessly duplicated inside the loop at line 18.

I suggest to calculate it in a spreadsheet (excel) before you program it. The first x rows will be the conditions, then every row is a date where a payment is due. The columns will be the variables you are using in the program.

Let me inform you, that this calculation is far from the real world loan calculation. Bicycle-car comparison comes to my mind. Both are vehicles. But this may not matter for you....

May I suggest that you group things together in functions to get a better view and clarity...

data_input
processing the data (calculation)
data_output

Give your functions and arguments/variables meaningful names to help readability.