Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this simple conditional expression not working? [duplicate]

Very simple line:

i = 3
a = 2 if i in [1, 3, 6] else a = 7

fails with:

SyntaxError: can't assign to conditional expression

whereas expanded as:

if i in [1, 3, 6]:
    a = 2
else:
    a = 7

works fine.

like image 933
Gabriel Avatar asked Oct 05 '15 17:10

Gabriel


People also ask

What are the 3 conditional operators?

There are three conditional operators: && the logical AND operator. || the logical OR operator. ?: the ternary operator.

Can if else always replace if?

We cannot replace every if/else statement with the conditional operator. There are two requirements for doing so: There has to be one expression in both the if and else block. When there are several lines of code in those blocks, then we cannot replace the if/else statement with the conditional operator.


2 Answers

You are using it wrong. Use it this way:

a = 2 if i in [1, 3, 6] else 7

The general form is:

var = val1 if cond else val2
like image 165
Aleksandr Kovalev Avatar answered Oct 18 '22 14:10

Aleksandr Kovalev


Should be

 a = 2 if i in [1, 3, 6] else 7

You can read it as:

 a = (((2 if i in [1, 3, 6] else 7)))

which is to say that the expression on the right side of the assignment sign is fully evaluated and the result then assigned to the left side. The expression itself is two values separated by the condition.

like image 34
Larry Lustig Avatar answered Oct 18 '22 14:10

Larry Lustig