8

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.

2 Answers 2

18

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Anand. I should have caught that. :) On a side note, seems like you answer all of my questions.
Guess I just answer alot of question :) .
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.