How to check if a number is within a range in Python?

2

In Python, I would like to check if a number is within a range.

Is there a more pythonic way than the following code?

if n >= 100 and n <= 200:
    ...
    
asked by anonymous 24.08.2016 / 19:25

3 answers

4

Use the following syntax:

if 100 <= n <= 2000:
    ... 
    
24.08.2016 / 19:25
1

Another alternative, however limited depending on what you check out is range :

numero = 101

if numero in range(100, 200):
    print ("{} está no intervalo!".format(numero))
else:
    print ("{} não consta no intervalo!".format(numero))

Note : In Python 2.x use xrange instead of range .

More information: In Python 2 is it more performative to use range or xrange ?

As mentioned by jsbueno , range does not work properly when using floating point , alternatively you can use expressions :

def xfrange(start, stop=None, step=None):
    if stop is None:
        stop = float(start)
        start = 0.0

    if step is None:
        step = 1.0

    cur = float(start)

    while cur < stop:
        yield cur
        cur += step

Font

More information: What is yield ?

Example usage:

if 5.5 in xfrange(0, 6.5, 0.5):
    print ("{} está no intervalo!".format(numero))
else:
    print ("{} não está no intervalo!".format(numero))

The above example checks whether 5.5 is within the range of 0 to 6.5 , from in> 0.5 at a time.

See DEMO

A second alternative using magic methods :

def inRange(inicio, final, n):
    try:
        return (inicio).__le__(n).__and__((final).__ge__(n))
    except:
        return None

The above function checks whether n is less than or equal and end is greater than or equal to n .

Example usage:

print (inRange(1, 10, 5))      # True  "5 >= 1 e 5 <= 10"
print (inRange(0.5, 5.0, 5.1)) # False "5.1 >= 0.5 e 5.1 > 5.0" 
print (inRange(0.4, 1.0, 0.6)) # True  "0.6 >= 0.4 e 0.6 <= 1.0"
print (inRange(0.1, 0.3, 0.4)) # False "0.4 >= 0.1 e 0.4 > 0.3"
print (inRange(0, 100, 55))    # True  "55 >= 0 e 55 <= 100"

See DEMO

These are some alternatives, use what is most appropriate and simple, as suggested in Fabio's answer .

    
24.08.2016 / 20:04
0

I think the most correct way is what you described:

if n >= 100 and n <= 200:

In my view the form:

if n in range(100, 201):

It will consume more resources unnecessarily since it will create a list of 100 values and will compare them 1 to 1.

However a slightly more elegant way would be:

if 100 <= n <= 200:
    
26.08.2016 / 11:25