The following code (the one below at the end) which according to me what it should do is show the sum of all the numbers, from 1 to the number entered by the user . Example: The user enters the number 6, and the result should show on the screen that the sum of the numbers is 21. (Because 1+2+3+4+5+6 = 21). But he gives me the answer 27 .
PS: Now how to solve it, is by changing the order of the counter and accumulator variables inside the While. Remaining accumulator first and counter after.
But I don't understand why it doesn't work the way I think it should.
contador = 1
acumulador = 0
maximo = int(input("Ingrese el número con el cual quiera sumar los anteriores: "))
while contador <= maximo:
contador = contador + 1
acumulador = acumulador + contador
print("La suma de los numeros es {}".format(acumulador))
If you put the line
contador = contador + 1
before the fromacumulador = acumulador + contador
, you would be starting the sum at2
and the last addend would ben+1
.So when
n = 6
the result is27 = 2 + 3 + 4 + 5 + 6 + 7
.If you leave the lines as you posted, the sum starts at
1
and ends atn
.