The difference between '+=' and '=+

2019-02-17 12:50发布

问题:

This question already has an answer here:

  • What's the purpose of the + (pos) unary operator in Python? 5 answers

So I have a simple piece of code that prints out the integers 1-10:

i = 0
while i < 10:
        i += 1
        print(i)

Then if you just change one operator around on line 3, it prints out an infinite amount of 1 integers(which i understand why it does that). Why isn't a syntax error occurring when running this second program? Wouldn't it call a syntax error in the event of an assignment operator being followed by an addition operator??

i = 0
while i < 10:
        i =+ 1
        print(i)

回答1:

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



回答2:

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.



回答3:

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



回答4:

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.



回答5:

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.