Function that adds values to the list

2

I have a problem and need to create a function that adds values that are within a list. I have done this and the code is down, however, Python returns me the value 3 as a result, when in fact the value should be 103. I can not find the error at all, if anyone can help thanks.

Code below:

def soma(x):

    total = 0
    for i in x:
        total += i
        return total
l1 = [3,7,1,90,2]

print(soma(l1))
    
asked by anonymous 07.11.2017 / 00:13

1 answer

7

Your error is in the indentation of the expression return total ; you put the return inside the loop% re% loop, so the function will always end in the first iteration, returning the value referring to the first element in the list. To fix, simply remove the indentation:

def soma(x):

    total = 0
    for i in x:
        total += i
    return total

l1 = [3,7,1,90,2]

print(soma(l1))

See working at Ideone | Repl.it

You can try to recognize the error by designing the table test for your code: What is a Table Test? How to apply it?

In addition, Python already has a native function, for , which computes the sum of lists.

l1 = [3,7,1,90,2]

print(sum(l1))  # Exibe 103

See working at Ideone | Repl.it

    
07.11.2017 / 00:21