tochau - 4 years ago 153

Python Question

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Yes as is stated in the documentation:

(...)

Comparisons can be

chained arbitrarily, e.g.,, except that`x < y <= z`

is equivalent to`x < y and y <= z`

`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,zare expressions andop1,op2, ...,opNare 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**