我正在为一个我正在关注的指南做一些python作业,而且我基本上想要我创建一个为某人设置投资的功能。这需要他们从多少开始,应用多少利息,以及他们将投入多少年。很简单......
我挂断了功能,以及部署它们的最佳方式。正如你在我的代码中看到的那样,我有一个功能设置,但它不能正常工作,我甚至都不打扰它。
相反,我有点大猩猩,让它输出我希望输出的东西,但我知道有一种更简单的方法可以做我做的事情。
我试图提出一个for循环来做一年投资到另一年的数学计算,但我无法理解。
另外,我知道第11-15行的缩进是关闭的,但那是因为我的for循环被注释掉了。代码工作正常,没有被注释掉。
欢迎和赞赏任何帮助或批评!
#function invest defines initial amount invested, interest, and over how many years
def invest(amount, rate, time):
for amount in invest:
amount = 5
print amount
return
mylist = [2000, .025, 5];
#for growth in "mylist[0, 1, 2]":
year1 = mylist[0] + (mylist[0] * mylist[1])
year2 = year1 + (year1 * mylist[1])
year3 = year2 + (year2 * mylist[1])
year4 = year3 + (year3 * mylist[1])
year5 = year4 + (year4 * mylist[1])
#invest(mylist);
print "prinicpal amount:", mylist[0]
print "annual rate of return:", mylist[1]
print "I am going to invest for", mylist[2], "years."
print
print "In doing, this I will see the following returns over the next 5 years:"
print "In the first year, I will see", year1
print "In the second year, I will see", year2
print "In the third year, I will see", year3
print "In the foruth year, I will see", year4
print "In the the fifth year, I will see", year5
答案 0 :(得分:1)
在与一位擅长Python工作的朋友一起工作之后,我们决定为我正在处理的这段代码做一些不同的事情。在听完我的建议和想法之后,很多这是他推荐的语法。然后他说了很多,你为什么要这样做呢?
新代码(使用compound
函数)采用我正在使用的相同参数,但随后允许您在调用脚本本身时传递参数,而不必每次都修改脚本你想要改变变量的时间。
因此,您现在可以调用脚本,然后添加:投资金额,利率,投入的时间以及每年在投资之上增加的额外收入。实施例..
python `invest.py 2000 .025 5 1000`
现在这样做可以准确地返回我想要的内容。我不能为这一个获得所有的功劳,但我确实想要至少展示一个我已经登陆的答案的例子。
由于David Robinson的建议,函数invest
就是我想出来的,函数compound
就是我朋友的建议。两者都可用,只需要注释另一个。
#!/usr/bin/python
#function invest defines initial amount invested, interest, and over how many years
import sys
def invest(amount, rate, time):
growth = (amount * rate)
# range generates a list, thus using memory
# xrange is a generator so it doesn't use all memory
for i in xrange(1, time + 1):
print 'Year {0}: {1}'.format(i, amount + (growth * i))
return growth
def compound(amount, rate, time, additional=0):
# range generates a list, thus using memory
# xrange is a generator so it doesn't use all memory
for i in xrange(1, time + 1):
amount += additional
amount = int(amount + (amount * rate))
print 'Year {0}: {1}'.format(i, amount)
if __name__ == '__main__':
args = sys.argv
time = 5
if len(args) > 1:
amount = int(args[1])
rate = float(args[2])
time = int(args[3])
additional = int(args[4])
compound(amount, rate, time=time, additional=additional)
#growth = invest(2000, .025, time=time)