Check if a given value is out of certain range

Tim Chase python.list at tim.thechases.com
Tue Sep 29 19:44:33 EDT 2015


On 2015-09-29 21:32, Mark Lawrence wrote:
> On 29/09/2015 17:48, Rob Gaddi wrote:
> >> Is there any similar elegant way to check if a value is out of
> >> certain range?
> >> Example - To check if x is either less than zero or greater than
> >> ten? Right now I am using x < 0 or x > 10.
> >
> > not (0 <= x <= 10)
> 
> Yuck.

Not sure there's much "yuck" to be had there.  It's succinct, easy to
read, and correct.  The only improvement might be if you have things
to do in both cases, in which case remove the "not" and set the
clauses accordingly:

  if 0 <= x <= 10:
    success_within_range(x)
  else:
    fail_out_of_bounds(x)

-tkc






More information about the Python-list mailing list