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.
You can clear up this invalid syntax in Python by switching out the semicolon for a colon. Here, once again, the error message is very helpful in telling you exactly what is wrong with the line.
The SyntaxError: cannot assign to operator error is raised when you try to evaluate a mathematical statement before an assignment operator. To fix this error, make sure all your variable names appear on the left hand side of an assignment operator and all your mathematical statements appear on the right.
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.
The Python SyntaxError occurs when the interpreter encounters invalid syntax in code. When Python code is executed, the interpreter parses it to convert it into bytecode. If the interpreter finds any invalid syntax during the parsing stage, a SyntaxError is thrown.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With