'How to calculate compound interest with different interest rates each year in python
The problem I am struggling with goes as follows:
Assume $500 is deposited in a savings account. The balance is incremented every year according to the following:
a) with a for loop calculate the “balance” in the savings account after 4 years with an interest rate of 0.8% per year.
b) then, assume that the interest in the following years is 1.2%, 1.5%, 1.3%, 1.7% respectively. Calculate the “balance” at the end of this 8-year period. This second part of the calculation SHOULD also be done with a for loop. Note that this time, you could use a list of values rather than the range function.
Write a sentence displaying the final value of “balance”, rounded to two decimal places.
This is my code:
a = 500
for x in range (4):
a = a + 1
b = a * 1.008
i = b
#code works this far
for y in (1.012,1.015,1.013,1.017):
i = y + 1
c = y * i
print("The balance after 8 years is ",c)
The sum after the first 4 years is correct but it seems like my for loop is only multiplying that number with the first value in my list.
Solution 1:[1]
Correcting the first loop and implementing the changing interest rate correctly gives:
a = 500
for _ in range(4):
a *= 1.008
print(f"The balance after 4 years is {a:.2f}")
b=a
for i in (1.012, 1.015, 1.013, 1.017):
b *= i
print(f"The balance after 8 years is {b:.2f}")
Output:
The balance after 4 years is 516.19
The balance after 8 years is 546.25
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
