[英]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.