Har
Har

Reputation: 3918

Why is b=(a+=1) an invalid syntax in python?

If I write the following in python, I get a syntax error, why so?

a = 1
b = (a+=1)

I am using python version 2.7

what I get when I run it, the following:

>>> a = 1
>>> b = (a +=1)
  File "<stdin>", line 1
    b = (a +=1)
        ^
SyntaxError: invalid syntax
>>>

Upvotes: 4

Views: 2919

Answers (4)

aga
aga

Reputation: 29434

All the answers provided here are good, I just want to add that you can achieve what you want in a one-line expression, but written in a different manner:

b, a = a+1, a+1

Here you're doing almost the same thing: incrementing a by 1, and assigning the value of a+1 to b - I'm telling 'almost' because here we have two summations instead of one.

Upvotes: 1

lvc
lvc

Reputation: 35089

Unlike in some other languages, assignment (including augmented assignment, like +=) in Python is not an expression. This also affects things like this:

(a=1) > 2

which is legal in C, and several other languages.

The reason generally given for this is because it helps to prevent a class of bugs like this:

if a = 1: # instead of ==
    pass
else:
    pass

since assignment isn't an expression, this is a SyntaxError in Python. In the equivalent C code, it is a subtle bug where the variable will be modified rather than checked, the check will always be true (in C, like in Python, a non-zero integer is always truthy), and the else block can never fire.

You can still do chained assignment in Python, so this works:

>>> a = 1 
>>> a = b = a+1
>>> a
2
>>> b
2

Upvotes: 7

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251106

a +=1 is a statement in Python and you can't assign a statement to a variable. Though it is a valid syntax in languages like C, PHP, etc but not Python.

b = (a+=1)

An equivalent version will be:

>>> a = 1
>>> a += 1
>>> b = a

Upvotes: 4

aIKid
aIKid

Reputation: 28302

As @Ashwini stated, a+=1 is an assigment, not a value. You can't assign it to b, or any variable. What you probably want is:

b = a+1

Upvotes: 2

Related Questions