贷款支付计算

时间:2016-02-14 02:22:49

标签: python python-3.x finance

我正在学习Python并且陷入困境。我正在努力寻找贷款支付金额。我目前有:

def myMonthlyPayment(Principal, annual_r, n):
    years = n
    r = ( annual_r / 100 ) / 12
    MonthlyPayment = (Principal * (r * ( 1 + r ) ** years / (( 1 + r ) ** (years - 1))))
    return MonthlyPayment

n=(input('Please enter number of years of loan'))
annual_r=(input('Please enter the interest rate'))
Principal=(input('Please enter the amount of loan'))

但是,当我跑步时,我会少量离开。如果有人能指出我的错误,那就太好了。我使用的是Python 3.4。

3 个答案:

答案 0 :(得分:3)

付款计算明智,您似乎没有正确翻译formula。除此之外,由于内置的​​input()函数返回字符串,因此在将值传递给期望它们为数值的函数之前,您需要将它返回的任何内容转换为正确的类型。

def myMonthlyPayment(Principal, annual_r, years):
    n = years * 12  # number of monthly payments
    r = (annual_r / 100) / 12  # decimal monthly interest rate from APR
    MonthlyPayment = (r * Principal * ((1+r) ** n)) / (((1+r) ** n) - 1)
    return MonthlyPayment

years = 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)))

答案 1 :(得分:0)

我认为在计算的最后一点,

/ (( 1 + r ) ** (years - 1))
你的包围错了;它应该是

/ ((( 1 + r ) ** years) - 1)

答案 2 :(得分:0)

我认为正确的公式就是这个,

MonthlyPayment = (Principal * r) / (1 - (1 + r) ** (12 * years))

我清理了一些变量,

def get_monthly_payment(principal, annual_rate, years):
    monthly_rate = annual_rate / 100 / 12
    monthly_payment = principal * (monthly_rate + monthly_rate / ((1 + monthly_rate) ** (12 * years) - 1))
    return monthly_payment

years = float((input('Please enter number of years of loan')))
annual_rate = float((input('Please enter the interest rate')))
principal = float((input('Please enter the amount of loan')))
print ("Monthly Payment: " + str(get_monthly_payment(principal, annual_rate, years)))

在输入周围添加try-except块也是明智的。

相关问题