Calculate a running total during a for loop - Python

橙三吉。 提交于 2019-12-04 22:39:04

Before your loop, initialize a variable to accumulate value:

total_paid = 0

And then, in the body of your loop, add the appropriate amount to it. You can use the += operator to add to an existing variable, e.g.

total_paid += 1

is a short form for total_paid = total_paid + 1. You don't want to give total_paid a new value each iteration, rather you want to add to its existing value.

I'm not sure about the specifics of your problem, but this is the general form for accumulating a value as you loop.

You always make the minimum payment? Just use minPayment instead of figuring out that math again. Keep a running total, then print it out after the loop.

balance = float(raw_input("Outstanding Balance: "))
interestRate = float(raw_input("Interest Rate: "))
minPayRate = float(raw_input("Minimum Monthly Payment Rate: "))
paid = 0

for month in xrange(1, 12+1):
    interestPaid = round(interestRate / 12.0 * balance, 2)
    minPayment = round(minPayRate * balance, 2)
    principalPaid = round(minPayment - interestPaid, 2)
    remainingBalance = round(balance - principalPaid, 2)
    paid += minPayment

    print  # Make the output easier to read.
    print 'Month: %d' % (month,)
    print 'Minimum monthly payment: %.2f' % (minPayment,)
    print 'Principle paid: %.2f' % (principalPaid,)
    print 'Remaining balance: %.2f' % (remainingBalance,)

    balance = remainingBalance

print
print 'RESULTS'
print 'Total amount paid:', paid
print 'Remaining balance: %.2f' % (remainingBalance,)

Also notice that range has exactly one value, so you'd just check month == 12, but it's simply not necessary here.

You actually have to initialize totalPaid to 0 and then

totalPaid = round(interestPaid + principalPaid, 2) + totalPaid

Inside the loop. Your problem is that you're not accumulating the total, you're just setting a new one on each iteration.

sounds like you were close. The problem is that you were overwriting the total each time. Try something like this:

totalPaid = totalPaid + round(interestPaid + principalPaid, 2)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!