Doubt while while

0

I have the following code:

# -*- coding: utf-8 -*-

def soma(lista):
    soma_num = 0
    while soma_num <= lista:
        soma_num += a
    return soma()
a = [1, 2, 3, 4]
print(soma(a))

I know that it will give error in line 7 and 10, saying that it is not possible to use the + = operator in list and integer. But my doubt and the following, in this code that I mounted can only be solved using the for loop or it is possible using the while loop. Or I would have to add a for inside the while. Well I have an example and it works perfectly with for loop.

    
asked by anonymous 22.06.2016 / 07:13

1 answer

2

Glaucous,

You can execute your sum function, either on a while loop or on a for loop.

def soma(lista):
    total = 0
    for item in lista:
        total += item
    return total

a = [1, 2, 3, 4]
print soma(a)

or else:

def soma(lista):
    total = 0
    index = 0
    while index < len(lista):
        total += lista[index]
        index += 1
    return total

a = [1, 2, 3, 4]
print soma(a)

Or as the function you want is already defined internally in python, you can simply:

a = [1, 2, 3, 4]
print sum(a)
    
22.06.2016 / 09:25