4

I want to do the following example in python:

x = 10 
y = 8

if x-5 <= y <= x+5:
     print(y)

I see that this is working, but I would like to know if it's "ok" like this, if there is a better solution or something I have to consider doing it like this.

Magdaanne
  • 145
  • 10
  • 4
    Yes, it's perfectly OK. Python is one of the few languages that allows this syntax. – Barmar Feb 10 '18 at 10:41
  • Don't try it in C, Javascript, PHP, though.... – Barmar Feb 10 '18 at 10:41
  • See [the official documentation](https://docs.python.org/2/reference/expressions.html#comparisons). `x-5 <= y <= x+5` is equivalent to `(x-5 <= y) and (y <= x+5)`, but less ugly. – dhke Feb 10 '18 at 11:09

1 Answers1

0

Chained expressions are acceptable in Python:

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

In fact, because and is lazy and the syntax is cleaner, they are preferable.

Just be aware that chained expressions take priority. For example, see Why does the expression 0 < 0 == 0 return False in Python?.

jpp
  • 159,742
  • 34
  • 281
  • 339