Function for Python Sum and Average

Asked

Viewed 61 times

-1

I am trying to develop these functions, when I type the numbers 1, 2, 3, 4 and 5, they return me the results 1 and 0,2. Can help me know what I’m doing wrong?

def soma(lista):
    soma_lista = 0
    for i in lista:
        soma_lista += i
        return soma_lista
        
def media(lista):
    media_lista = soma(lista) / len(lista)
    return media_lista

lista = list()

for i in range(5):
    num = float(input('Números: '))
    lista.append(num)

print('A soma dos seus números é',soma(lista),'e a média deles é',media(lista),'.')
  • 2

    Not knowing the numbers you typed becomes difficult to know, but a guess is that in function soma the return is inside the for, and I was sure to be out

  • Good observation, I tidied up the post, were 1,2,3,4,5

  • Kkkkk was right, my God saw... some things so, obvious, thank you for your help!

1 answer

2

In the first function your Return needs to stay out of the loop, so:

def soma(lista):
    soma_lista = 0
    for i in lista:
        soma_lista += i
    return soma_lista

Browser other questions tagged

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