Check if a given value is out of certain range

BartC bc at freeuk.com
Wed Sep 30 20:32:22 CEST 2015


On 29/09/2015 05:46, Laxmikant Chitare wrote:
> Hi,
> I know there is an elegant way to check if a given value is within
> certain range.
> Example - To check if x is between zero and ten, I can do 0 < x 10.

That's not clear. Do you mean whether x is 1 to 9 inclusive? Because 
your contrary example below suggests you mean 0 to 10 inclusive.


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

You might try just defining a function to do it:

  def out_of_range(x,a,b):
	# use whatever code you like

then use it as: if out_of_range(x,0,10):

But it is necessary to define exactly what is meant by it (Python ranges 
seem to exclude the upper bound). So x<0 or x>10 might not be the most 
elegant, and x is evaluated twice, but it is the clearest.

-- 
Bartc


More information about the Python-list mailing list