1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Trouble with Python sum function

  1. Nov 12, 2011 #1
    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<



    3. The attempt at a solution

    Code (Text):
    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)
     
  2. jcsd
  3. Nov 12, 2011 #2

    Mark44

    Staff: Mentor

    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
     
  4. Nov 13, 2011 #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.
     
  5. Nov 13, 2011 #4

    Mark44

    Staff: Mentor

    Yes, that's exactly what was happening.
    You're welcome! We enjoy being able to help out.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Trouble with Python sum function
Loading...