#loop syntax help

1 messages · Page 1 of 1 (latest)

mellow coral
#

if I have an input x, and let's say I wanted to count by 2, I would put "x+=2"
I notice some codes with loops use "x=x+2" in this case of counting by 2.
Is there any difference? If so what is it

terse gulch
#

tldr: x+=2 is basically calling x=x+2 for you.

x+2 gets the value of x adds the value of 2 and stores the result back into x


referring to documentation of +=
Python has the magic methods
__add__() which is used with the + operator
and __iadd__() used by the += operator
the i in iadd stands for inplace.
inplace is when you modify the value being read/used

For instance, if x is an instance of a class with an __iadd__() method, x += y is equivalent to x = x.__iadd__(y)
Otherwise, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y
https://docs.python.org/3/reference/datamodel.html#object.__iadd__
there is a default implementation of __add__ and ect when you don't write your own