tochau tochau - 4 years ago 153
Python Question

Python shorthand for multiple conditionals in an if statement

if x == y != z:
print (x + y)


Is this shorthand for if x == y and y != z? It works in my code, but I'm unsure how multiple conditionals are interpreted when they are not all == or !=, or otherwise written out in the latter form above.

Answer Source

Yes as is stated in the documentation:

(...)

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

So you can chain any kind of comparator: <, >, ==, >=, <=, <>, !=, is [not], and [not] in.

The documentation further makes it more formal:

Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.

So for instance:

'a' in 'ab' in 'zabc'

is equivalent to:

'a' in 'ab' and 'ab' in 'zabc'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download