2017-01-29 107 views
-4

我正在嘗試在網站上創建貸款計算器,並且在編寫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)) 

任何有經驗的人都可以幫助我獲得此編碼中的語法或其他邏輯錯誤嗎?

+0

'loaninyears'沒有定義。您將乘以12. – MYGz

+0

'print(「付款將是」+ st(monthlypayment))'我認爲'st'應該是'str'這裏 – MYGz

+0

金額應該可能是貸款金額,並且您從不給每月付款一個非零值 –

回答

1

您正在閱讀之前未聲明的變量。 更改loaninyearsloandurationinyearsloanamount

另外,你必須在最後一行一個錯字,ST應該海峽

也有一些小竅門:

首先,你可以做的東西,如:

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

這這樣可以縮短程序的長度。

而且你可能要考慮使用一個更可讀的變量命名,例如:

loanInYearsloan_in_years

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