shooqie - 1 year ago 94
Python Question

# 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?

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download