我正在尝试在网站上创建一个贷款计算器,我在编写Python时遇到了麻烦。代码是:
# user enter the cost of the loan, the interest rate, and
#the number of years for the loan
#Calculate monthly payments with the following formula
# M = L[i(1+i)n] / [(1+i)n-2]
# M = monthly payment
# L = Loan amount
# i = interest rate (for an interest rate of 5%, i = 0.05)
# n = number of payments
#________________________________________________________________________#
#Start of program
#Declare variables
monthlypayment = 0
loanamount = 0
interestrate = 0
numberofpayments = 0
loandurationinyears = 0
loanamount = raw_input("Lending Money ")
interestrate = raw_input("Interest Rates are? ")
loandurationinyears = raw_input("Time Duration in Years?")
#Convert the strings into floating numbers so we can use them in the formula
loandurationinyears = float(loandurationinyears)
loanamount = float(loanamount)
interestrate = float(interestrate)
#Since payments are once per month, number of payments is number of years for the loan
payments = loaninyears*12
#calculate the monthly payment based on the formula
payment = amount * interestrate * (7+ interestrate) * payments / ((1 + interestrate) * payments -1)
#Result to the program
print("Payment will be " + st(monthlypayment))
任何有经验的人都可以帮助我在编码中获取语法或其他逻辑错误吗?
答案 0 :(得分:1)
您正在阅读之前未声明过的变量。 将 loaninyears 更改为 loandurationinyears 和金额更改为 loanamount 。
此外,你在最后一行有一个拼写错误, st 应该 str
还有一些提示:
首先,您可以执行以下操作:
input = float(raw_input("Give me some number"))
这样可以缩短程序的长度。
另外,您可能需要考虑使用更易读的变量命名,例如:
loanInYears 或 loan_in_years
答案 1 :(得分:0)
在评论中仔细遵循您的公式,并使用Python 2.7,这会运行,但结果是不正确的。
# user enter the cost of the loan, the interest rate, and
#the number of years for the loan
#Calculate monthly payments with the following formula
# M = monthly payment
# L = Loan amount
# i = interest rate (for an interest rate of 5%, i = 0.05)
# n = number of payments
L = input ('loan amount')
i = input ('interest rate')
n = input ('nr of payments')
M = L*(i*(1+i)*n) / ((1+i)*n-2)
print (M)
我认为除了编码错误之外,你应该先修改你的公式。 具体来说,我错过了某个地方的12号,因为你的兴趣是每年,但你的付款是每月。
[编辑]
在这里看看Joshy的答案:
Formula for calculating interest Python
并且可能使用不同的视频教程,因为这个教程似乎让很多人陷入困境。
提示:ifyouhaveverylongvariablenames you_may_place_some_underscores_in_them