[英]How do I change a variable in a for loop in python?
我試圖用python編寫一個程序,計算信用卡上的余額。 它是針對MIT開放式課件“計算機科學與程序設計導論” 。 我正在做第一個問題 。
該程序必須詢問用戶初始變量:初始余額,年利率和每月最低還款額。 這是我的代碼。
initialOutstandingBalance= float(raw_input('What is the outstanding balance on your
card?'))
annualInterestRate=float(raw_input('What is the annual interest rate expressed as a
decimal?'))
minimumMonthlyPaymentRate=float(raw_input('What is the minimum monthly payment rate on
your card expressed as a decimal?'))
for month in range(1,13):
print("Month: "+ str(month))
minimumMonthlyPayment=float(minimumMonthlyPaymentRate*initialOutstandingBalance)
interestPaid=float((annualInterestRate)/(12*initialOutstandingBalance))
principalPaid=float(minimumMonthlyPayment-interestPaid)
newBalance=float(initialOutstandingBalance-principalPaid)
print("Minimum monthly payment: $"+str(minimumMonthlyPayment))
print("Principle paid: $"+str(principalPaid))
print("Remaining Balance: $"+str(newBalance))
如何獲取剩余余額以正確更新? 我不知道如何在每個月底更新余額。 到目前為止,每個月對於最低每月還款額,已付本金和剩余余額返回相同的值。
您在整個循環中使用相同的initialOutstandingBalance
變量,並且從不對其進行更改。 相反,您應該跟蹤當前余額。 這將等於循環開始時的初始未償余額,但是會隨着循環的進行而變化。
您也不需要繼續調用float
。
current_balance = initialOutstandingBalance
for month in range(1,13):
print("Month: "+ str(month))
minimumMonthlyPayment = minimumMonthlyPaymentRate * current_balance
# this calculation is almost certainly wrong, but is preserved from your starting code
interestPaid = annualInterestRate / (12*current_balance)
principalPaid = minimumMonthlyPayment - interestPaid
current_balance = current_balance - principalPaid
print("Minimum monthly payment: $"+str(minimumMonthlyPayment))
print("Principle paid: $"+str(principalPaid))
print("Remaining Balance: $"+str(current_balance))
您希望將變量newBalance
保留在循環之外,否則將在每次迭代時將其重新分配。 同樣,您也不想將利率除以余額的12倍,而是將其除以12,然后再將商乘以余額。 最后,如上所述,您不需要所有的float
。
這應該工作:
newBalance = initialOutstandingBalance
for month in range(1,13):
print("Month: " + str(month))
minimumMonthlyPayment = minimumMonthlyPaymentRate * newBalance
interestPaid = annualInterestRate / 12 * newBalance
principalPaid = minimumMonthlyPayment - interestPaid
newBalance -= principalPaid
print("Minimum monthly payment: $" + str(minimumMonthlyPayment))
print("Principle paid: $" + str(principalPaid))
print("Remaining Balance: $" + str(newBalance))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.