Function adding values within the list

Asked

Viewed 129 times

2

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

Code below:

def soma(x):

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

print(soma(l1))

1 answer

7


Your mistake is in the indentation of the expression return total; you put the return inside the loop of repetition for, thus the function will always end in the first iteration, returning the value referring to the first element of the list. To fix, just 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 on Ideone | Repl.it

You can try to recognize the error by preparing the table test for your code: What is a Table Test? How to Apply It?

In addition, Python already has a native function, sum, calculating the sum of lists.

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

print(sum(l1))  # Exibe 103

See working on Ideone | Repl.it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.