Python,为什么这个求和函数不起作用
这个求和函数为什么不管用呢?它的目的是把列表中的变量项加起来。
def sum_list (a_list):
length= len(a_list)
counter = 0
total= 0
while(counter < length):
(a_list[counter] +total)
total = total + counter
counter = counter + 1
return total
#testing the functions
my_list = [3,3,3]
print sum_list(my_list)
1 个回答
0
首先,length
这个东西没有定义过,但你却在while循环的条件里用到了它。这会导致你看到的错误。你可以用len(list)
来获取你列表的长度。
其次,你的while循环里面其实没有在用到列表的值:(list[counter] + total)
这行代码并没有做什么,因为它没有把结果赋值给任何东西。
最后,total = total + counter
并不是在加值,而是在加每个值的位置。所以在这个例子中:0 + 1 + 2
,如果你解决了我刚才提到的length
的问题,结果会是3
,而不是正确的9
。
更新
最后(又一次),你甚至没有用my_list = [3,3,3]
来测试你的函数,根本没有提到你上面定义的那个函数。你只是创建了一个列表而已。