python - Future Value of yearly investments -
suppose have investment plan invest fixed amount @ beginning of every year. compute total value of investment @ end of last year. inputs amount invest each year, interest rate, , number of years of investment.
this program calculates future value of constant yearly investment. enter yearly investment: 200 enter annual interest rate: .06 enter number of years: 12 value in 12 years is: 3576.427533818945
i've tried few different things, below, doesn't give me 3576.42, gives me $400. ideas?
principal = eval(input("enter yearly investment: ")) apr = eval(input("enter annual interest rate: ")) years = eval(input("enter number of years: ")) in range(years): principal = principal * (1+apr) print("the value in 12 years is: ", principal)
if it's yearly investment, should add every year:
yearly = float(input("enter yearly investment: ")) apr = float(input("enter annual interest rate: ")) years = int(input("enter number of years: ")) total = 0 in range(years): total += yearly total *= 1 + apr print("the value in 12 years is: ", total)
with inputs, outputs
('the value in 12 years is: ', 3576.427533818945)
update: responding questions comments, clarify what's going on:
1) can use int()
yearly
, same answer, fine if invest whole number of currency. using float works allows amount 199.99
, example.
2) +=
, *=
convenient shorthand: total += yearly
means total = total + yearly
. it's little easier type, more important, more expresses meaning. read this
for in range(years): # each year total += yearly # grow total adding yearly investment total *= 1 + apr # grow total multiplying (1 + apr)
the longer form isn't clear:
for in range(years): # each year total = total + yearly # add total , yearly , assign total total = total * (1 + apr) # multiply total (1 + apr) , assign total
Comments
Post a Comment