34 python floating-point sequence
级别:初学者
为什么我得到错误"不能将序列乘以'int'类型的非int"?
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])
Run Code Online (Sandbox Code Playgroud)
谢谢巴巴
Jer*_*own 19
for i in growthRates:
fund = fund * (1 + 0.01 * growthRates) + depositPerYear
Run Code Online (Sandbox Code Playgroud)
应该:
for i in growthRates:
fund = fund * (1 + 0.01 * i) + depositPerYear
Run Code Online (Sandbox Code Playgroud)
您将使用growthRates列表对象乘以0.01.将列表乘以整数是有效的(它是重载的语法糖,允许您创建包含其元素引用副本的扩展列表).
例:
>>> 2 * [1,2]
[1, 2, 1, 2]
Run Code Online (Sandbox Code Playgroud)
jat*_*ism 13
Python允许您将序列相乘以重复其值.这是一个视觉示例:
>>> [1] * 5
[1, 1, 1, 1, 1]
Run Code Online (Sandbox Code Playgroud)
但它不允许您使用浮点数来执行此操作:
>>> [1] * 5.1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
Run Code Online (Sandbox Code Playgroud)