Print only the negatives

Asked

Viewed 23 times

0

lista = [12, -2, 4, 8, 29, 45, 78, 36, -17, 2, 12, 8, 3, 3, -52]

for n in lista:
    if n < 0:
    soma_dos_negativos = sum(n)
print('A soma dos elementos negativos é igual a {}'.format(soma_dos_negativos))

1 answer

2

You are making an incorrect use of the function sum, sending an integer number, being that it expects an eternal object:

soma_dos_negativos = sum(n)

A possible correction would be to declare the variable soma_dos_negativos before in the for:

soma_dos_negativos = 0

And in the if within the for, add up the negative numbers in the same:

soma_dos_negativos += n

The complete code would look more or less like this:

lista = [12, -2, 4, 8, 29, 45, 78, 36, -17, 2, 12, 8, 3, 3, -52]

soma_dos_negativos = 0

for n in lista:
  if n < 0:
    soma_dos_negativos += n

print('A soma dos elementos negativos é igual a {}'.format(soma_dos_negativos))

See online: https://repl.it/@Dadinel/HandmadePointedAtoms


If you want to use the function sum, it is possible to send the list already filtering the negative numbers, would be more or less as follows:

soma_dos_negativos = sum([n for n in lista if n < 0])

Full example:

lista = [12, -2, 4, 8, 29, 45, 78, 36, -17, 2, 12, 8, 3, 3, -52]

soma_dos_negativos = sum([n for n in lista if n < 0])

print('A soma dos elementos negativos é igual a {}'.format(sum([n for n in lista if n < 0])))

See online: https://repl.it/@Dadinel/SaneImpracticalDirectory

Using the sum that way, it would even be possible to leave all this code in one line:

print('A soma dos elementos negativos é igual a {}'.format(sum([n for n in [12, -2, 4, 8, 29, 45, 78, 36, -17, 2, 12, 8, 3, 3, -52] if n < 0])))

Documentation: https://docs.python.org/3/library/functions.html#sum

Browser other questions tagged

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