我正在尝试在互联网上找到的这个复利问题:
A = P(1 + r)n,其中P是投资金额,r是年度百分比率(小数5.0%= 0.050),n是投资年数.
3列表代表投资,费率和条款
investment = [10000.00, 10000.00, 10000.00, 10000.00, 1.00]
rate = [5.0, 5.0, 10.0, 10.0, 50.00]
term = [20, 40, 20, 40, 40]
Run Code Online (Sandbox Code Playgroud)
我制作了这样的程序,但我感觉不是像我一样写出来的东西,我可以使用一个叫做循环的东西,但是我不知道我每次都能正确地使用for循环,我搞砸了:
rateindecimal = [int(rate[0])/100.0, int(rate[1])/100.0, int(rate[2])/100.0), int(rate[3])/100.0, int(rate[4])/100.0]
Run Code Online (Sandbox Code Playgroud)
我将百分比率转换为小数,但是如何使用循环来运行速率列表并轻松转换?
然后我做了这个.我觉得它太重复了,再一次,我觉得我需要一个循环,但我不是很擅长使用一个...
A1 = int(Investment[0]) * (1 + ratedecimal[0])**int(term[0])
A2 = int(Investment[1]) * (1 + ratedecimal[1])**int*term[1])
Run Code Online (Sandbox Code Playgroud)
等等...
print "$" + str(round(A1, 2))
print "$" + str(round(A2, 2))
Run Code Online (Sandbox Code Playgroud)
等等.
如果这真的很长,我很抱歉.我只想知道如何循环使用所有这些,所以我不必如此重复.
谢谢!
用zip()它们将它们压缩在一起,然后.format()输出:
for investment, rate, term in zip(investments, rates, terms):
A = investment * (1 - rate / 100) ** term
print '${0:.02f}'.format(A)
Run Code Online (Sandbox Code Playgroud)