Search code examples
pythonloopsfor-loopaccumulator

Beginner Python Code Issue: Accumulator Loop


I am a beginner programmer and I am working on an assignment that requires me to do nested loops as part of a finance operation. I have written most of the code and the numbers work according (such as interest and such), however the issue arises when I try print out the savings summary for the years given.

import math

def main():

    #This will be hardcoded values for the years running, savings amount and annual interest             and calculate the monthly interest rate

    savingsAmount = 500
    annualInterest = 0.12
    yearsRunning = 2

    monthlyInterest = annualInterest / 12

    #This will state the accumulator variables for totals of investment balance (month), savings (YTD), and interest earned (YTD)

    totalInvestBal = 0
    totalSavings = 500
    totalInterest = 0

    #This will begin the accumulator loop process

    for i in range (1, yearsRunning + 1):
        print "Savings Schedule for Year", i,":"
        print "Month    Interest    Amount  Balance"
        for i in range (1, 13):
            totalInterest = monthlyInterest * totalInvestBal
            totalInvestBal = totalSavings + totalInterest + totalInvestBal
            totalSavings = totalSavings
            print i, round(totalInterest,2), round(totalSavings,2), round(totalInvestBal,2)         
        print 
        #i becomes 12 here so we need another answer.
        print "Savings summary for year", (need a new way of saying the year here),":"
        print "Total amount saved:", totalSavings
        print "Total interest earned:", totalInterest
        print "End of year balance:", totalInvestBal


main()

Since the "i" loop index variable is updated to 12, I can place that as the year. I am working from year 1 up and I need the savings summary to be from year 1 and up as well. How would that be fixed?


Solution

  • Simply change the second loop variable form i to anything else (e.g. k):

    for i in range (1, yearsRunning + 1):
        print
        print "Savings Schedule for Year", i,":"
        print "Month    Interest    Amount  Balance"
        for k in range (1, 13):
            totalInterest = monthlyInterest * totalInvestBal
            totalInvestBal = totalSavings + totalInterest + totalInvestBal
            totalSavings = totalSavings
            print k, round(totalInterest,2), round(totalSavings,2), round(totalInvestBal,2)         
        print 
        #IF WE KEEP ONLY i IT becomes 12 here so we need another -> VARIABLE!!!!! for example K!!.
        print "Savings summary for year %s:" %(i) #use this " words words %s words" %(variable name)
        print "Total amount saved:", totalSavings
        print "Total interest earned:", totalInterest
        print "End of year balance:", totalInvestBal