Home > Enterprise >  How can I get an output of a compound interest for every year of the time the amount is invested, us
How can I get an output of a compound interest for every year of the time the amount is invested, us

Time:09-21

this is the code I have written, I couldn't get the expected result. I always get one amount that repeats 8 times.

amount = float(input('the principal amount: '))
rate = float(input('annual rate of return: '))
time = int(input('how many years it will take: '))

def invest(amount, rate, time):
    total = amount * (1 rate)**time
    print(total)

for t in range(time):
    total_new = amount * (1 rate)**time
    print(total_new)

invest(amount, rate, time)

expected outpout for invest(100, 0.05, 8):

year1: $105
year2: $110.25
year3: $115.7625
.
.
.
.
.
year8: $147.745544379

CodePudding user response:

Your function is correct, the problem is only in your for loop. It should be like this:

for t in range(time):
    total_new = amount * (1   rate) ** t
    print(total_new)

Your mistake was setting everything to the power of time, instead of to the power of t. The variable t was changing, while time stayed the same, so you got the same result 8 times.

Besides that, I would also suggest using parenthesis around (1 rate) ** t just to make it clear that it is happening before the multiplication by amount.

CodePudding user response:

You need to change your variable in the loop, put t instead of time:

        for t in range(1,time):
          total_new = amount * (1 rate)**t
          print(total_new)
  • Related