Python Forum

Full Version: Please tell me what i did wrong
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
sample_list = [8, 2, 3, 0, 7]
print("Sample list: %s " % sample_list)

def sum_list(lists):
    for x in lists:
        total = total + lists[x]
    return total
    

print("Sum of all the number in the list: "),
print(sum_list(sample_list))

raw_input("\nPress ENTER to exit") 
 
I was told to create a function that can sum up all the elements in a list and this is what I came up with.
It didn't work
Please help
What have you done to debug the program then?
I bet there was an error message. Something like this:
Output:
Traceback (most recent call last): File "C:\Users\djhys\Documents\Python\Musings\junk.py", line 11, in <module> print(sum_list(sample_list)) File "C:\Users\djhys\Documents\Python\Musings\junk.py", line 6, in sum_list total = total + lists[x] UnboundLocalError: local variable 'total' referenced before assignment
Given that, you don't need any help debugging. The error was on line 6 of sum_list. THe error type was UnboundLocalError. Additional information was supplied saying 'total" was referenced before assignment.

So what is the value of total before you start summing items from the list?
I did not assign the total variable with any value before the summing begin.
Is that why the error appears?

Thanks, I got it now