Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Operator (+=) and SyntaxError

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.

like image 246
Charles Avatar asked Aug 03 '15 02:08

Charles


People also ask

How do I fix invalid SyntaxError in Python?

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.

How do you fix SyntaxError Cannot assign to operator?

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.

Why is += giving me SyntaxError?

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.

What is a SyntaxError in Python?

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.


2 Answers

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
like image 89
Anand S Kumar Avatar answered Sep 17 '22 15:09

Anand S Kumar


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.

like image 32
BlivetWidget Avatar answered Sep 17 '22 15:09

BlivetWidget