The difference between ‘+=’ and ‘=+’? [duplicate]

Posted on

Question :

The difference between ‘+=’ and ‘=+’? [duplicate]

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)
Asked By: faceless

||

Answer #1:

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

Answered By: Kittsil

Answer #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.

Answered By: ShadowRanger

Answer #3:

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

Answered By: Ned Batchelder

Answer #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.

Answered By: Mercury

Answer #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.

Answered By: Fantastic Mr Fox

Leave a Reply

Your email address will not be published.