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

Emile van Sebille emile at fenx.com
Sun Jun 7 17:48:27 CEST 2009

```On 6/7/2009 8:44 AM Emile van Sebille said...
> 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
>>

Besides the obvious typo you've got there and I cut and paste below.
(+ threshold twice instead of +/- threshold)

Emile

>
> 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
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

```