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

Asked

Viewed 12,149 times

2

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

There is a more pythonic way than the following code?

if n >= 100 and n <= 200:
    ...

3 answers

4


Use the following syntax:

if 100 <= n <= 2000:
    ... 

1

Another alternative, however limited depending on what is verified is the 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 it is more performative to use range or xrange?

Like mentioned by jsbueno, the range does not work properly when using numbers from floating point, as an alternative, one 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

Source

More information: What is the purpose of the yield?

Example of use:

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, of 0.5 in 0.5 at a time.

See DEMO

A second alternative using magical 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 equal to or equal to to beginning and if final is greater or equal to n.

Example of use:

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 suitable and simple, as suggested in response from Fabio.

  • 2

    It is important to note that this alternative checks whether 100 <= n < 200 and not 100 <= n <= 200. Moreover, this solution only works for integers, since Python will check whether numero is present in list intervalo.

  • 2

    This is not a good way - if ofr in Python 3, and your number is always an integer, it works well - if it is in Python2, where the range returns a list, the performance will be painful - and anyway, if it is a float number, the result will always be false. This is a good example of how nay do.

  • @jsbueno I’ve edited the answer and made it clear...

  • @downvoter motif??

  • 1

    The downvoter was me - with the new editions, it’s okay.

0

I believe the most correct form is the one you described:

if n >= 100 and n <= 200:

The way I see it:

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 shape would be:

if 100 <= n <= 200:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.