我是一名初学者程序员,我正在处理一项要求我将嵌套循环作为财务操作的一部分的任务。我已经编写了大部分代码,并且数字根据(例如利息等)工作,但是当我尝试打印给定年份的储蓄摘要时出现了问题。
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()
由于“i”循环索引变量更新为 12,我可以将其作为年份。我从第一年开始工作,我也需要从第一年开始的储蓄摘要。那将如何解决?