Python operator (+ =) and SyntaxError
Ok, what am I doing wrong?
x = 1 print x += 1
Mistake:
print x += 1
^
SyntaxError: invalid syntax
Or, +=
no longer works in Python 2.7? I would swear that I have used it in the past.
+3
Cu Hh
source
to share
2 answers
x += 1
is the augmented Python assignment operator .
You cannot use assertions inside a print statement, which is why you get a syntax error. You can use Expressions .
You can do -
x = 1 x += 1 print x
+9
Anand s kumar
source
to share
I would recommend to logically separate what you are trying to do. This will make your code cleaner and, more often than not, code that behaves the way you really want it to. If you want to increase x before printing, do this:
x = 1
x += 1
print(x)
>>> 2 # with x == 2
If you want to print x before increasing it:
x = 1
print(x)
x += 1
>>> 1 # with x == 2
Hope it helps.
+1
BlivetWidget
source
to share