Python编码问题贷款计算

2024-05-15 04:25:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一个网站上创建一个贷款计算器,我在编写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))

有没有经验的人能帮我弄清楚这段代码的语法或其他逻辑错误吗?在


Tags: ofthenumberforrawratepaymentformula
2条回答

您正在读取以前未声明的变量。 将贷款年数改为贷款年数金额改为贷款额。在

另外,最后一行有一个打字错误,st应该是str

还有一些提示:

首先,你可以做如下事情:

input = float(raw_input("Give me some number"))

这样可以缩短程序的长度。在

此外,您可能需要考虑使用更具可读性的变量命名,例如:

贷款年数贷款年数

严格遵循注释中的公式,并使用Python2.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,因为你的利息是每年的,但你的付款是每月的。在

[编辑]

看看乔希的回答:

Formula for calculating interest Python

也许使用不同的视频教程,因为这一个似乎让很多人陷入困境。在

小贴士:如果你有很长的变数,你可以在它们上面加上一些下划线

相关问题 更多 >

    热门问题