0

there is a function I want to define that takes all items in a list and adds them up together:

def sum():

for x in range(len(user)):
    sum = 0
    sum =+ user[x]
    return sum

user = [1,1,1]
score = sum()
print(score)

for some reason it prints just 1, and my wanted output is 3.

  • Fix the indentation of the shown code (if you do it right, it will also solve your problem). – Michael Butscher Jul 02 '22 at 17:31
  • 1
    Why would you want to obliterate the *sum()* built-in function? – DarkKnight Jul 02 '22 at 17:33
  • And please not re-define the built-in `sum` as it'll shadow some future use. – Daniel Hao Jul 02 '22 at 17:35
  • You're resetting sum to 0 on _each_ loop iteration. Don't do that. Move `sum = 0` to be above the loop. Also you have a `return` inside the loop, which will exit the function immediately. Move the `return` to be after the loop. – John Gordon Jul 02 '22 at 17:48

4 Answers4

0

You re-define sum for each x which means that your sum is always user[x]. Additionally, you return immediately after the first x element.

A possible solution is this:

def sum(user):
    sum = 0
    for u in user:
        sum += u
    return sum

print(sum([1,1,1]))
lukasl-dev
  • 724
  • 3
  • 11
0

Given a list of integers you could do this:

my_list = [1, 1, 1]

def accumulation(list_):
  total = 0
  for i in list_:
    total += i
  return total

...or...

sum(my_list) # where sum is the Python built-in function
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

I think you have forgotten to ident your for loop:

def sum():

for x in range(len(user)):
    sum = 0
    sum =+ user[x]
    return sum

user = [1,1,1]
score = sum()
print(score)

should be...

def sum():

    for x in range(len(user)):
        sum = 0
        sum =+ user[x]
    return sum

user = [1,1,1]
score = sum()
print(score)

...to achieve your expected result.

Mike L
  • 1
  • 1
0

All the above answers work. Bu I was thinking, why not use sum(list) ? It would return the same output as expected but a lot less code.

Obiii
  • 698
  • 1
  • 6
  • 26