Search code examples
pythonoperatorsassignment-operator

why does x -= x + 4 return -4 instead of 4


new to python and trying to wrestle with the finer points of assignment operators. Here's my code and then the question.

  x = 5
  print(x)
  x -= x + 4
  print(x)

the above code, returns 5 the first time, but yet -4 upon the second print. In my head I feel that the number should actually be 4 as I am reading this as x= x - x +4. However, I know that is wrong as python is returning -4 instead. I would be gracious if anyone could explain to me (in simple terms as I am a novice) as I have been really pounding my head over the table on this one.


Solution

  • x -= x + 4 can be written as:

    x = x - (x + 4) = x - x - 4 = -4