problem in condition while "assignment operators"


Hello, I have a problem that I do not understand when using assignment operators

the exercise is about printing a sum from 50 + 48 + 46 + 44 ... 20

h=0 #que hace esta variable?

while n<=20:
  h+=n #no entiendo lo que hace esto
  n -=2


Aqui tendria que salir la suma de todos los numeros desde el 50 al 20
asked by Rebc3sp 22.05.2018 в 17:58

1 answer


h = 0 #what does this variable do?

The variable "h" is an accumulator, that is, it is responsible for saving the sum of each value of "n" while executing the loop while


h + = n #I do not understand what this does

That is an abbreviation of the following operation:

h = h + n

That is, an abbreviation that indicates that you save the value of "n" in "h" to "accumulate" it while the loop is executed while .


the exercise is about printing a sum from 50 + 48 + 46 + 44 ... 20

This means that you are looking to add those even numbers for which there is the operation n%2 which means divide "n" successively by 2 to its minimum expression (integer). We know that an even number is the one whose final residue is 0 so we can use the following conditional in Python:


This conditional would read: if the remainder of "n" is 0 (is even) then it executes the internal operation of the if.

I must tell you that your code has an error because if you take into account those numbers for when "n" is between 20 and 50 then the condition of the while must be : n>=20 , as "n" starts at 50 you just have to check that the process stops when it reaches 20 (including 20 as you requested).

Taking into account everything mentioned above, you would have the new code that does exactly what you need:


while n>=20:

I hope it helps. Greetings!

answered by 22.05.2018 / 18:17