Why does this sum function not work? It’s intent is to sum the variable items in a list
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)
First,
lengthis not defined anywhere, but you are trying to use it in the while condition. That would cause the error you are probably seeing. The length of your list can be obtained withlen(list).Second, your while body isn’t actually using the list values:
(list[counter] +total)isn’t doing anything, as it’s not assigned to anything.Finally,
total = total + counterisn’t adding the values, instead, it’s adding the positions of each value. So, in this example:0 + 1 + 2, which , if you fix thelengthproblem I mentioned first, you’d end up with3, instead of the correct value of9.Update
Finally (again), you are not even testing the function with your
my_list = [3,3,3], there’s no mention of the function you defined above. Instead, you’re just creating a list.