shooqie - 1 year ago 80

Python Question

In Java or C we have

`<condition> ? X : Y`

`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`

`or`

Answer Source

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`

)