Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

X and Y or Z - ternary operator

In Java or C we have <condition> ? X : Y, which translates into Python as X if <condition> else Y.

But there's also this little trick: <condition> and X or Y.

While I understand that it's equivalent to the aforementioned ternary operators, I find it difficult to grasp how and and or operators are able to produce correct result. What's the logic behind this?

like image 759
shooqie Avatar asked Aug 22 '16 13:08

shooqie


Video Answer


1 Answers

While I understand that it's equivalent to the aforementioned ternary operators

This is incorrect:

In [32]: True and 0 or 1
Out[32]: 1

In [33]: True and 2 or 1
Out[33]: 2

Why the first expression returns 1 (i.e. Y), while the condition is True and the "expected" answer is 0 (i.e. X)?

According to the docs:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

So, True and 0 or 1 evaluates the first argument of the and operator, which is True. Then it returns the second argument, which is 0.

Since the True and 0 returns false value, the or operator returns the second argument (i.e. 1)

like image 99
awesoon Avatar answered Oct 14 '22 06:10

awesoon