Doubt while loop

Asked

Viewed 85 times

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 it will give error on line 7 and 10, saying it is not possible to use the operator += in list and integer. But my question is the next one, in this code that I have built only and possible to solve using the for loop or it is possible using the while loop. Or I would have to add a for in while. For I have an example and it works perfectly with for loop.

1 answer

2


Glaucio,

you can perform your summation function both in a loop while how much in a loop for.

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)
  • Rubico that my doubt even, in the loop for I could quietly. I was having trouble in the same while.

  • 1

    was missing a Return there, but I think I got the idea. I’ll arrange ;)

  • I got the idea yes, it was worth it.

Browser other questions tagged

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