Trouble with Python sum function

  • #1
49
0
I don't know why we have to write a sum function for python when there already is one but
this is supposed to sum a list with varible values and I don't understand why it doesn't work, can someone help explain there error, I believe that I am not giving proper values to the line that adds but I don't realize why<



The Attempt at a Solution



Code:
def sum_list (a_list):
    length = len(a_list)
    counter = 0
    total= 0
    
    while(counter < length):
                              
        (a_list[counter] +total)          
    
        counter = counter + 1
    total = total + counter    
    return total      



#testing the functions
my_list = [3,3,3]


print sum_list(my_list)
 

Answers and Replies

  • #2
I don't know why we have to write a sum function for python when there already is one but
this is supposed to sum a list with varible values and I don't understand why it doesn't work, can someone help explain there error, I believe that I am not giving proper values to the line that adds but I don't realize why<



The Attempt at a Solution



Code:
def sum_list (a_list):
    length = len(a_list)
    counter = 0
    total= 0
    
    while(counter < length):
                              
        (a_list[counter] +total) <<< Problem is here         
    
        counter = counter + 1
    total = total + counter    
    return total      



#testing the functions
my_list = [3,3,3]


print sum_list(my_list)

Your while loop isn't right. Python evaluates a_list[counter] + total for each element in the array, but you aren't storing the value anywhere.

You need something like this:
total = total + a_list[counter]

Then get rid of the line that says total = total + counter
 
  • #3
Thanks that's fixed.

To understand my mistake and clarify; is it fair to say that every time the loop ran it was adding 3 to zero then chucking that value into nothing as opposed to saving it, that's why the print was 3?

Again thankyou, I learn more here with a few of my mistakes and all your replies then my instructors teach.
 
  • #4
Thanks that's fixed.

To understand my mistake and clarify; is it fair to say that every time the loop ran it was adding 3 to zero then chucking that value into nothing as opposed to saving it, that's why the print was 3?
Yes, that's exactly what was happening.
Again thankyou, I learn more here with a few of my mistakes and all your replies then my instructors teach.
You're welcome! We enjoy being able to help out.
 

Suggested for: Trouble with Python sum function

Replies
2
Views
138
Replies
2
Views
302
Replies
3
Views
214
Replies
1
Views
525
Replies
1
Views
486
Replies
10
Views
1K
Replies
6
Views
302
Replies
24
Views
921
Back
Top