24

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)
mkrieger1
  • 14,486
  • 4
  • 43
  • 54
faceless
  • 396
  • 1
  • 2
  • 11

5 Answers5

50

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

Kittsil
  • 2,169
  • 12
  • 20
6

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

Ned Batchelder
  • 345,440
  • 70
  • 544
  • 649
6

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.

ShadowRanger
  • 124,179
  • 11
  • 158
  • 228
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.

Mercury
  • 5,904
  • 2
  • 34
  • 45
0

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.

Fantastic Mr Fox
  • 30,083
  • 25
  • 91
  • 165