Python Forum
Please tell me what i did wrong
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Please tell me what i did wrong
#1
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
Reply
#2
What have you done to debug the program then?
Reply
#3
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?
Reply
#4
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
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020