为什么我会从以下代码中得到“无法将序列与非整型‘浮点数’相乘”的错误?
def nestEgVariable(salary, save, growthRates): SavingsRecord = [] fund = 0 depositPerYear = salary * save * 0.01 for i in growthRates: fund = fund * (1 + 0.01 * growthRates) + depositPerYear SavingsRecord += [fund,] return SavingsRecord print nestEgVariable(10000,10,[3,4,5,0,3])
for i in growthRates: fund = fund * (1 + 0.01 * growthRates) + depositPerYear
应为:
for i in growthRates: fund = fund * (1 + 0.01 * i) + depositPerYear
您正在将 0.01 与 growthRates 列表对象相乘。将列表与整数相乘是有效的(这是重载语法糖,允许您使用其元素引用的副本创建扩展列表)。
例子:
>>> 2 * [1,2] [1, 2, 1, 2]