How to add up several numbers that were typed in the output?

Asked

Viewed 787 times

0

What I got so far:

for c in range(3):
    n = int(input())
    n += n #tenho quase certeza que essa parte não está certa
print(n)

How to add up several numbers that were typed in output?

  • It’s not adding up correctly.

  • The variable that receives the total must be created outside the loop

2 answers

2


You’re overwriting the value of n when you do n = int(input()), does before:

total = 0
for _ in range(3):
    n = int(input())
    total += n
print(total)

DEMONSTRATION

Or with fewer lines/variables:

total = 0
for _ in range(3):
    total += int(input())
print(total)

Python style:

total = sum(int(input()) for _ in range(3))
  • You can explain better what you did?

  • You were nullifying the previous value of n when you were doing n = int(input()), then you were just adding it up to itself (equivalent to n*2) in the next line

  • In the stretch n = int(input()) inside the loop you declared the variable again and it lost the value of the previous sum n += n

0

You can use the following code...

valores = list(map(int, input('Digite todos os valores: ').split()))
print(f'\033[32mA soma dos valores digitados é: {sum(valores)}')

See how this code works on repl it..

When we executed this code, we received the following message...

Digite todos os valores:

Right now we must type todos the values we desire, in the mesma line, separated by a espaço and then press the button enter.

If, for example, we want to enter the values 3, 4, 5, 6, when the program requests the typing of the values, we must type as follows:

3 4 5 6

...and then press enter.

From that time the program will calculate the sum of all values that were typed and stored in the list valores.

Also note, that this code adds an amount of undefined values and, to end the typing, just press enter.

In other words, if you type 3 values and pressure enter 3 values will be added.

Now, if you type 100 values and press enter, 100 values will be added.

Browser other questions tagged

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