Reputation: 2301
Why assignment fails at else part ? I was trying to increment two variables based on a condition in below one line .
>>> a=0
>>> b=0
>>> a+=1 if True else b
>>> a
>>> 1
>>> a if True else b+=1
File "<input>", line 1
SyntaxError: can't assign to conditional expression
>>> a if False else b+=1
File "<input>", line 1
SyntaxError: can't assign to conditional expression
>>> a+=1 if False else b
>>> a
>>> 1
>>> a+=1 if True else b+=1
File "<input>", line 1
a+=1 if True else b+=1
^
SyntaxError: invalid syntax
Upvotes: 0
Views: 4737
Reputation: 1502
In python, in a single line, the right side of assignment operator you can't use assignment again.
for example a = b + (c = d)
, cannot be done in python.
Referring to above example again:
b = 10
a = 20
a+=1 if True else b # this is valid.
a+=1 if False else b # this is valid.
a if True else b+=1 # this is invalid.
a if False else b+=1 # this is invalid.
a+=1 if True else b+=1 # this is invalid.
t = a if True else b=1 # this is invalid.
In these statements, if we try to print
a if True else b
would have printed b value.
But above code, trying to use assignment in the expression, it will not be allowed in python.
This kind of syntax is allowed in C language, but not in python. For example, in C-language we can write like
if (a=10): printf("%d", a);
Will actually does assignment inside the condition to a and pass the condition and executes if part.
In python, it just throws an error if you write code as:
if a=10: print a
one can only write in python like
if a==10 : print a
Upvotes: 4
Reputation: 112
The reason is the meaning of the syntax x if cond else y
in python. What this syntax mean is not operation_a if condition else operation_b
but rather value_a if condition else value_b
This means the correct way of using it is
var = val1 if condition else val2
And not:
var1=val1 if condition else var2=val2
Read more at:details about if else oneliner operator
P.S: using a hack like:
(var1=val1) if condition else (var2=val2)
Might work, but don't use it since it is not pythonic and the return value of this statement is not obvious at first glance ("explicit is better then implicit")
Upvotes: -1
Reputation: 16404
a+=1 if True else b
is parsed as
a += (1 if True else b)
In Python, assignment is not an expression.
Upvotes: 4