如果是年度投资,则应每年添加:
yearly = float(input("Enter the yearly investment: "))
apr = float(input("Enter the annual interest rate: "))
years = int(input("Enter the number of years: "))
total = 0
for i in range(years):
total += yearly
total *= 1 + apr
print("The value in 12 years is: ", total)
有了你的输入,这个输出
('The value in 12 years is: ', 3576.427533818945)
更新:从评论中回答您的问题,以澄清发生了什么:
1)你可以使用int()
foryearly
并得到相同的答案,如果你总是投资整数货币,这很好。例如,使用浮点数同样有效,但也允许金额199.99
为 。
2)+=
并且*=
是方便的简写:total += yearly
表示total = total + yearly
. 它更容易打字,但更重要的是,它更清楚地表达了意思。我是这样读的
for i in range(years): # For each year
total += yearly # Grow the total by adding the yearly investment to it
total *= 1 + apr # Grow the total by multiplying it by (1 + apr)
较长的形式并不那么清楚:
for i in range(years): # For each year
total = total + yearly # Add total and yearly and assign that to total
total = total * (1 + apr) # Multiply total by (1 + apr) and assign that to total