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.
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.
Yes as is stated in the documentation:
(...)
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < 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 toa 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'