为什么x - = x + 4返回-4而不是4

时间:2023-01-26 11:47:55

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

python的新手,并试图与赋值运算符的细节点搏斗。这是我的代码,然后是问题。

  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.

上面的代码,第一次返回5,但第二次打印时返回-4。在我脑海中,我觉得这个数字实际上应该是4,因为我正在读这个数字x = x - x +4。但是,我知道这是错误的,因为python正在返回-4。如果有人能向我解释(简单来说,因为我是一个新手),我会很亲切,因为我真的在这个桌子上敲了敲我的头。

1 个解决方案

#1


14  

x -= x + 4 can be written as:

x - = x + 4可写为:

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

#1


14  

x -= x + 4 can be written as:

x - = x + 4可写为:

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