Home > OS >  Pythonic "or" operation
Pythonic "or" operation

Time:02-13

In python I can write an expression like 3 < a < 10 and it gets evaluated with an and condition.

That is, 3 < a < 10 is a syntactic sugar for: 3 < a and a < 10

Is there a similar pythonic way to write it as an or condition?

CodePudding user response:

a < 3 or a > 10 is what I would write.

If you had 3 >= a or a >= 10 you could use de Morgan's laws to turn the or into an and, resulting in not (3 < a < 10).

For the specific case of checking if a number is out of range you could use a not in range(3, 11). A neat trick, but the 11 being off by one bugs me. I'd stick with or, myself.

  • Related