Check if a given value is out of certain range

Grant Edwards invalid at invalid.invalid
Wed Sep 30 11:56:31 EDT 2015


On 2015-09-30, alister <alister.nospam.ware at ntlworld.com> wrote:
> On Tue, 29 Sep 2015 18:44:33 -0500, Tim Chase wrote:
>
>> 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
>
> I would stick with the OP's current solution
>
> Readability Counts!

I'm baffled.

If the condition we are trying to check for is when "x is not within a
range of 0-10 inclusive" then this is as readable as it gets:

  not (0 <= x <= 10)         (I)

That's pretty much a literal, word-for-word translation of the
requirement into code.

Sure, you can can apply De Morgans theorom to transform that into

   (x < 0) or (x > 10)       (II)

That's just as correct, but now the code is one step removed from the
requirement statement.

IMO, (I) is _more_ readable than (II)
   
-- 
Grant Edwards               grant.b.edwards        Yow! Boy, am I glad it's
                                  at               only 1971...
                              gmail.com            



More information about the Python-list mailing list