Reputation: 9
I need some help in this program. I need help figuring out how to make it calculate interest for a period over ten years (including the first one). This is as far as i have gotten on my own. I would greatly appreciate some insight to this problem.
Thanks. *The "print() is just for spacing so that the program looks cleaner.
p= int(input(" Intial Amount? "))
print()
r= float(input(" Rate? (Decimal) "))
print()
n= int(input(" Number Of Times Compunded? (Yearly) "))
print()
t= float(input(" Number Of Years? "))
A= p*(1+r/n)**(n*t)
print()
print( " Interest At Final Year","$",format(A, ',.2f'))
print()
for i in range (10):
print(format(i+1, '3')," Year","Interest","$",format(A,',.2f'))
Upvotes: 0
Views: 10740
Reputation: 6281
In the body of your loop, you are not updating the values of any of the variables. You need to update A at every iteration or store the intermediate results in some other variable. As an example, see the following:
def compound_interest(r, n, initial):
current_value = initial
for i in range(n):
current_value *= (1 + r)
print(current_value)
I use the current_value variable to save the intermediate results of the loop. If I had simply done initial * (1 + r) at every iteration then the value of initial would never change; the result of the calculation must be saved if you want to keep using it.
Upvotes: 3
Reputation: 366213
At the very end of the program it will count 1-10 but it will have the same amount as the first calculation.
Yes, that's because the only thing that happens in that loop is the print
call. You're just calculating A
all at once, before you get into the loop, and then using the same A
over and over again.
I need help making it add the new values to add up while the "n" and the "p" are changing.
Well, you aren't changing n
or p
, and I don't think you need to. But you do need to change something. If you want to print a different value of A
each time through the loop, you have to recalculate next year's A
based on the previous year's A
, or whatever else goes into determining the right value.
For example:
for year in range (10):
jan1balance = p
for period in range(n):
p = p * (1 + r)
print(format(year+1, '3')," Year","Interest","$",format(p - jan1balance,',.2f'))
Or:
for year in range (10):
yearlyinterest = 0
for period in range(n):
periodinterest = p * r
yearlyinterest += periodinterest
p += periodinterest
print(format(year+1, '3')," Year","Interest","$",format(yearlyinterest,',.2f'))
Upvotes: 0