【问题标题】:Python Coding Issue for Loan Calculator贷款计算器的 Python 编码问题
【发布时间】:2017-06-14 16:26:46
【问题描述】:

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

有经验的人可以帮我解决这个编码中的语法或其他逻辑错误吗?

【问题讨论】:

  • loaninyears 未定义。你将它乘以 12。
  • print("Payment will be " + st(monthlypayment)) 我认为st 应该是str
  • amount 应该是 loanamount 并且你永远不会给monthlypayment 一个非0 的值

标签: python calculator


【解决方案1】:

您正在读取之前未声明的变量。 将 loaninyears 更改为 loandurationinyears 并将 amount 更改为 loanamount

另外你在最后一行有错字,st 应该是 str

还有一些提示:

首先,您可以执行以下操作:

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

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

另外你可能想考虑使用更易读的变量命名,例如:

loanInYearsloan_in_years

【讨论】:

    【解决方案2】:

    密切遵循 cmets 中的公式,并使用 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,因为您的利息是每年,但您的付款是每月。

    [编辑]

    在这里看看乔希的答案:

    Formula for calculating interest Python

    也许使用不同的视频教程,因为这似乎给很多人带来了麻烦。

    提示:如果你有很长的变量名 you_may_place_some_underscores_in_them

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多