I am learning Python and am stuck. I am trying to find the loan payment amount. I currently have:
def myMonthlyPayment(Principal, annual_r, n):years = nr = ( annual_r / 100 ) / 12MonthlyPayment = (Principal * (r * ( 1 + r ) ** years / (( 1 + r ) ** (years - 1))))return MonthlyPaymentn=(input('Please enter number of years of loan'))
annual_r=(input('Please enter the interest rate'))
Principal=(input('Please enter the amount of loan'))
However, when I run, I am off by small amount. If anyone can point to my error, it would be great. I am using Python 3.4.
Payment calculation-wise, you don't appear to have translated the formula correctly. Besides that, since the built-in input()
function returns strings, you'll need to convert whatever it returns to the proper type before passing the values on to the function which expects them to numeric values.
def myMonthlyPayment(Principal, annual_r, years):n = years * 12 # number of monthly paymentsr = (annual_r / 100) / 12 # decimal monthly interest rate from APRMonthlyPayment = (r * Principal * ((1+r) ** n)) / (((1+r) ** n) - 1)return MonthlyPaymentyears = int(input('Please enter number of years of loan: '))
annual_r = float(input('Please enter the annual interest rate: '))
Principal = int(input('Please enter the amount of loan: '))print('Monthly payment: {}'.format(myMonthlyPayment(Principal, annual_r, years)))