One of the reasons the code doesn’t work is the lack of identation after the if
:
if n < 0:
soma_dos_negativos = sum(n)
It causes a IndentationError
. For the code to be executed only if n
is negative, you have to imagine:
if n < 0:
soma_dos_negativos = sum(n)
But that alone won’t solve, because according to the documentation, sum
must receive an eternal (i.e., a list, a tuple, etc., and it returns the sum of the elements of this eternal). Only you’re passing a number (every iteration of for
, the variable n
assumes one of the values of the list, which in this case only has numbers), and numbers are not eternal (so this code also gives error).
Anyway, there’s no point in using sum
with a number (since sum
serves to return the sum of the elements of an iterable). And even if it made sense, your code is overriding the value of soma_dos_negativos
with each iteration. Instead, you should add the value of each number to this variable (not forgetting to initialize it with zero):
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 # some o valor de n ao total já computado
print('A soma dos elementos negativos é igual a {}'.format(soma_dos_negativos))
But if you want, you can change the for
by a Generator Expression, succinct and pythonic:
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(soma_dos_negativos))
Now I can use sum
, for the Generator Expression is eternal. In this case, it takes only the negative numbers from the list, and sum
returns the sum of these.
Another option is to use filter
to filter the elements you want, and then pass the result to sum
:
soma_dos_negativos = sum(filter(lambda n: n < 0, lista))
The filter
gets a lambda which checks whether the number is negative, thereby filtering the negative numbers from the list, which in turn are passed to sum
, which returns the sum of these.
Not directly related, but if you are using Python >= 3.6, you can use f-strings to display the message:
print(f'A soma dos elementos negativos é igual a {soma_dos_negativos}')