假设您有一个投资计划,您可以在每年年初投资一定的固定金额。计算去年年底投资的总价值。投入将是每年投资的金额,利率和投资年数。
此程序计算未来值 每年不变的投资。 输入年投资:200 输入年利率:.06 输入年数:12 12年的价值是:3576.427533818945
我尝试了一些不同的东西,比如下面的内容,但它并没有给我3576.42,它只给我400美元。有什么想法吗?
principal = eval(input("Enter the yearly investment: "))
apr = eval(input("Enter the annual interest rate: "))
years = eval(input("Enter the number of years: "))
for i in range(years):
principal = principal * (1+apr)
print("The value in 12 years is: ", principal)
答案 0 :(得分:2)
如果是年度投资,您应该每年添加:
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()
用于yearly
并获得相同的答案,如果您始终投入大量货币,则可以。使用float也可以,但也允许使用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
答案 1 :(得分:0)
根据评论中的建议,您不应在此处使用eval()
。 (有关eval的更多信息,请参见in the Python Docs)。 - 相反,请将代码更改为使用float()
或int()
(如果适用),如下所示。
此外,您的print()
语句打印出括号和逗号,我希望您不要这样做。我在下面的代码中清理了它,但如果你想要的是你可以随意把它放回去。
principal = float(input("Enter the yearly investment: "))
apr = float(input("Enter the annual interest rate: "))
# Note that years has to be int() because of range()
years = int(input("Enter the number of years: "))
for i in range(years):
principal = principal * (1+apr)
print "The value in 12 years is: %f" % principal
答案 2 :(得分:0)
可以通过分析来完成:
X1 X2 X3 T
1 0 0 21
0 0 1 32
0 1 0 19

同样,如果您想要计算出需要投入的金额,那么您可以获得一定的数量,您可以这样做:
"""
pmt = investment per period
r = interest rate per period
n = number of periods
v0 = initial value
"""
fv = lambda pmt, r, n, v0=0: pmt * ((1.0+r)**n-1)/r + v0*(1+r)**n
fv(200, 0.09, 10, 2000)