3
I don’t understand why this code r += v
sum 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}")
3
I don’t understand why this code r += v
sum 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}")
10
r += v
does not sum values in an iteration. It is an expression that accumulates value. It does not matter where it was used. If you’re inside an interaction then the buildup is done inside.
The operator +=
is called compound because it does two things. It performs a sum and an assignment of value at the same time. This code is the same as writing:
r = r + v
So you’re taking the current value of r
and adding to the current value of v
. And in the same operation keeping the result of 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 add in r
.
The algorithm is accumulation, the operator is only a facilitator to give this semantics (in some languages in the past was used for optimization, but nowadays has language that does not optimize even using the compound syntax and has language that optimizes even does not use this syntax).
She took candy from the mouth of a child! The child was me. : -) finally I only had +1
Browser other questions tagged python python-3.x logic
You are not signed in. Login or sign up in order to post.
The title was correct. when it comes to a question the "why" is separated.
– Augusto Vasques