-2

I'm trying to update a multiplicative value to a variable.

I know that I can do += and -= for addition and subtraction and *= for multiplication, but I don't fully grasp the entirety of that type of operation. Can someone point me to the documentation that covers this? I can't seem to find it on python.org.

Logan
  • 439
  • 4
  • 10

1 Answers1

1

Well technically you are never updating python variables (integers, strings and floats among many other are immutable), you are re-assigning a value to a name.

+ is shorthand for add(), * is shorthand for mul() and - is short for sub().

since you are re-assigning variable, you are essentially performing these operations (when adding, substracting, multiplying, dividing or whatever it is that you do):

 a = 1
 a = a + 1     # a = 2
 a = a * 2     # a = 4
 a = a - 1     # a = 3

+=, -= and *= are just shorts for the above expressions.

i.e. the above can be restated as:

 a = 1
 a += 1
 a *= 2
 a -= 1

python docs for operators: https://docs.python.org/3.5/library/operator.html see also python docs for inplace operators for more information: https://docs.python.org/3.5/library/operator.html#inplace-operators

Christian W.
  • 2,532
  • 1
  • 19
  • 31