Python Operator (+=) and SyntaxError

15,190

Solution 1

x += 1 is an augmented assignment statement in Python.

You cannot use statements inside the print statement , that is why you get the syntax error. You can only use Expressions there.

You can do -

x = 1
x += 1
print x

Solution 2

I would recommend logically separating out what you're trying to do. This will make for cleaner code, and, more often than not, code that behaves like you actually want it to. If you want to increment x before printing it, do:

x = 1
x += 1
print(x)
>>> 2  # with x == 2

If you want to print x before incrementing it:

x = 1
print(x)
x += 1
>>> 1  # with x == 2

Hope that helps.

Share:
15,190
Charles
Author by

Charles

Updated on June 05, 2022

Comments

  • Charles
    Charles almost 2 years

    Ok, what am I doing wrong?

    x = 1
    
    print x += 1
    

    Error:

    print x += 1
             ^
    SyntaxError: invalid syntax
    

    Or, does += not work in Python 2.7 anymore? I would swear that I have used it in the past.

  • Charles
    Charles over 8 years
    Thanks Anand. I should have caught that. :) On a side note, seems like you answer all of my questions.
  • Anand S Kumar
    Anand S Kumar over 8 years
    Guess I just answer alot of question :) .