# [Tutor] creating a range above & below a given number

Emile van Sebille emile at fenx.com
Sun Jun 7 17:44:41 CEST 2009

On 6/7/2009 7:08 AM Gonzalo Garcia-Perate said...
>  the solution laid somewhere in between:
>
> def within_range(self, n, n2, threshold=5):
>         if n in range(n2-threshold, n2+threshold+1) and n <
> n2+threshold or n > n2 + threshold : return True
>         return False
>

Be careful here -- you probably will get stung mixing ands and ors
without parens.

>>> print False and False or True
True
>>> print False and (False or True)
False

The range test here can only serve to verify n as an integer, so you can
simplify to:

def within_range(self, n, n2, threshold=5):
if n == int(n) and (
n < n2+threshold or n > n2 + threshold) :
return True
return False

Of course, the test in the function is a boolean, so you can return the
result of the boolean directly and eliminate the return True and False
statements:

def within_range(self, n, n2, threshold=5):
return n == int(n) and (
n < n2+threshold or n > n2 + threshold)

Emile