如何消除“TypeError: 不能用非整数类型的'float'乘以序列”?
我正在学习Python,想找一个退休基金模拟器,这个模拟器需要三个参数:工资(salary
)、你想存的工资百分比(save
),还有一个投资年增长百分比的列表(growthRates
)。最后一个参数的长度决定了你打算工作多少年;growthRates[0]
是第一年的增长率,growthRates[1]
是第二年的增长率,依此类推。
我在运行程序时遇到了这个错误:
TypeError: can't multiply sequence by non-int of type 'float'
我写的代码是:
def ret_fund():
a = int(input("Enter Salary: "))
b = int(input("Enter Saving Percentage: "))
c = list(input("Enter List of Growth Rates per Year (must be zero for first year): "))
ans_list=[]
x = 1
global x
for i in c:
float(i)
x = x*(1+0.01*i)+(a*b*0.01)
ans_list.append(x)
print (ans_list)
我就是搞不清楚错误出在哪里。请帮我看看。还有那个变量c
呢?它实际上并没有按照程序的要求接收一个list
作为输入。我必须输入像05643
这样的数字,它们一个一个被选中。如果我想输入像[0, 5, 6, 4, 3]
这样的内容该怎么办呢?
2 个回答
2
问题出在 global x
这行代码上,它会覆盖本地的 x
赋值。我猜测全局的 x
是某种列表。
编辑:之前这个回答里有一段读取增长率的代码是错误的。
要读取一组增长率,你应该把它作为一个整体字符串来读取,然后把这个字符串拆分开,最后把每一部分转换成你需要的格式。单独使用 input
方法是无法正确处理的。
c = raw_input("Enter List of Growth Rates per Year (must be zero for first year): ")
for i in c.split():
i=float(i)
2
这段话的意思是,float(i)
这个写法其实没有任何作用。如果你想要把 i
变成浮点数,应该用 i=float(i)
,或者在你的公式里直接用 float(i)
替代 i
,因为它只出现了一次。
根据用户输入的内容,input()
会返回相应的对象。如果你输入 0.0, 1.0, 2e10, 99
,你会得到一个包含浮点数和整数的元组,所以没有必要再转换什么,因为比如说 0.01*x
在任何情况下都会被转换成浮点数。举个例子:
>>> a=input("enter numbers: ")
enter numbers: 1,2,3.0, 5e-10, 99
>>> print type(a), repr(a)
<type 'tuple'> (1, 2, 3.0, 5e-10, 99)
>>> for i in a: print i, type(i)
...
1 <type 'int'>
2 <type 'int'>
3.0 <type 'float'>
5e-10 <type 'float'>
99 <type 'int'>
>>> for i in a: print 0.01*i, type(0.01*i)
...
0.01 <type 'float'>
0.02 <type 'float'>
0.03 <type 'float'>
5e-12 <type 'float'>
0.99 <type 'float'>