What happens is that input
returns a string, and you tried to add these strings to the number that is in soma
. Then you must use int
to convert the string to number.
But there are other details. No need to declare the list with any values, because it can start empty and you add the elements as they are read.
And the input
accepts the message as parameter, so you don’t need to print it before.
Would look like this:
numeros = []
for x in range(1, 4):
numeros.append(int(input(f"Digite o valor {x}")))
soma = 0
for n in numeros:
soma += n
# ou se quiser usar o que já tem pronto
soma = sum(numeros)
I also changed the range
to go from 1 to 3, so you don’t need to add 1 to print.
Note that the sum should start at zero, not at 1. But only if you want to calculate manually, because there is already the function sum
who does it for you.
As to the for var in var
of its code: I confess that I was surprised to see that it works, but anyway I would not use a variable of loop with the same name on the list, as this only makes the code more confusing.
For the record, another way to create the list is by using comprehensilist on:
numeros = [ int(input(f"Digite o valor {x}")) for x in range(1, 4) ]
The return of function
input
at all times is a string, you need to convert to whole before using it.– Woss
@phduarte About the edition: no need to put the name of the language after the
\
``` because the system already uses the tags of the question to know which is the language and applies the correct syntax Highlight (and since it already had the tag [tag:python], so it was all right - it would only make sense if the code block was in another language (different from the question tags) or when the question has more than one language tag - which was not the case). See more on https://meta.stackexchange.com/q/184108/401803– hkotsubo
great tip @hkotsubo. thanks! In case the language is explicit, this causes loss of some level?
– phduarte
@phduarte In this case I think it makes no difference, Highlight will be the same (which is another reason not to need to do this type of editing, because it is not necessary) :-)
– hkotsubo
You’re absolutely right. Thanks.
– phduarte