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

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


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


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.