1
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.

username
  • 75
  • 5
  • Also see http://stackoverflow.com/questions/28754726/how-do-chained-comparisons-in-python-actually-work which shows how chained comparisons work at the bytecode level. – PM 2Ring Feb 06 '17 at 00:30

1 Answers1

5

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'
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555