0
weight = [10, 3, 7, 9, 6, 5, 2]

def listsum(numlist):
    sum = 0
    for i in numlist:
        sum = sum + i
    return sum

listsum(weight)  

I have this simple function to add the values of weight together and am expecting a total of 42 however when I run the function, I don't get any errors or anything.

I am not sure what's going on and have been trying to search various answers for the past 20 mins to no avail. Can someone point me in the right direction here? Thank you

5
  • 1
    Works fine for me...print(listsum(weight)) Commented Jul 19, 2018 at 18:48
  • are you indicating that there is no output? Commented Jul 19, 2018 at 18:49
  • 4
    Do not shadow built-ins. Use S or my_sum instead of sum. Commented Jul 19, 2018 at 18:49
  • just an fyi you can also do def listsum(numlist): return sum(numlist) Commented Jul 19, 2018 at 18:50
  • How are you attempting to run this code? if this is from an interactive window, did you remember to hit "ENTER" after your last line? If you're running from the command line, there's no output because you didn't print anything. Commented Jul 19, 2018 at 18:50

3 Answers 3

2

Just an fyi, you can use the built-in sum() function to do the same thing, or if you want a function with the built-in, you can do

def listsum(list):
    return sum(list)

Your function works perfectly; you just need to wrap the function call in a print() statement so you can see the output:

print(listsum(weight))

Sign up to request clarification or add additional context in comments.

Comments

1

Probably don't need to make a new function to do this, but is working fine for me.

>>> weight = [10, 3, 7, 9, 6, 5, 2]
>>> def listsum(numlist):
...     sum = 0
...     for i in numlist:
...         sum = sum + i
...     return sum
... 
>>> listsum(weight)
42

1 Comment

Please, don't use images to give examples. Use formated text
1

I didn't print(listsum(weight)) so the value wasn't showng...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.