Why does x + = y sum the values in an iteration?

I'm not understanding why this code r += v add up the values. I would like someone to explain to me why the output of this Code:

for c in range (0, 10):
    v = int(input("numero: "))
    r += v
print(f"resultado: {r}")
Author: Maniero, 2020-06-26

1 answers

r += v it does not sum values in an iteration. It is an expression that accumulates value. It doesn't matter where it was used. If it's inside an interaction then the buildup is done in there.

The operator += is called a compound, because it does two things. It performs a sum and a value assignment at the same time. This code is the same as writing:

r = r + v

Then you are taking the current value of r and adding it with the current value of v. And in the same operation holding the result this sum in r, which therefore changes its value and, in this code used, in the next iteration will be this new value considered to sum in r.

The algorithm is accumulation, the operator is only a facilitator to give this semantics (in some languages in the past it was used for optimization, but nowadays there is language that does not optimize even using the composite syntax and there is language that optimizes even does not use this syntax).

 11
Author: Maniero, 2020-06-29 14:09:32