[Solved] Python, why does this sum function not work


First, length is 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 with len(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 + counter isn’t adding the values, instead, it’s adding the positions of each value. So, in this example: 0 + 1 + 2, which , if you fix the length problem I mentioned first, you’d end up with 3, instead of the correct value of 9.

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.

solved Python, why does this sum function not work