The difference between '+=' and '=+'? [duplicate]

可紊 提交于 2019-12-01 03:58:07

i+=1 is the same as i=i+1, whereas i=+1 just means i=(+1).

Tokenizers don't typically require spaces unless it's necessary to disambiguate (e.g. you need a space, or punctuation of some form between a variable name and a language keyword so the keyword can be recognized).

Thus, x=+y, x =+ y and x = +y are all equivalent, in all cases invoking the unary + operator on y and assigning to x. The unary plus operator isn't commonly used, but just because it's uncommon doesn't mean it's not recognized and accepted.

For comparison, the --> "operator" in C/C++ etc. is another example where humans looking for spaces and tokenizers ignoring them causes confusion.

i =+ 1 is the same as i = +1, or i = 1.

x=+1 is treated as: x=(+1)
while x+=1 is treated as: x=x+1

There are binary operators which operates on their left-handside operand and their right-hand side operand (e.g. * multiplication).
And there are unary operators which takes only right-hand side operand (e.g. ~/! negation). There are operators which can be unary and binary.

The plus sign in python can be used also as right-hand side operator just as minus.

Python Docs:

The unary - (minus) operator yields the negation of its numeric argument.

The unary + (plus) operator yields its numeric argument unchanged.

There is no syntax error because the expression i =+ 1 is the same as i = (+1) and +1 is perfectly legitimate. It is a unary operator, not the addition operator.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!