Is there a better way to check if a number is range of two numbers

If by better, you mean faster, it's a good idea to check the lower and upper limits, as the previous comments/answers have suggested.

However, note that in Python3, the range() object does this for you, resulting in the in range() check being a nearly constant time operation, so I don't think the runtime should be bad using your code.

I'd highly recommend reading this thread:

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?


If there are many ranges your solution becomes very verbose. You may want to give this (simpler) code a try:

limits = (0, 5500, 9500, 14500, 19500, 24500, 29500, 34500, 39500, 44500)

def checkRange(number):
    for i, (low, high) in enumerate(zip(limits[:-1], limits[1:]), 1):
        if low <= number < high:
            return 5000*i
    return 0  # when the passed number is out of range

It is worth pointing out that your logic has an off-by-one error, whereas in my implementation this issue is fixed.

Demo:

In [188]: checkRange(5499)
Out[188]: 5000

In [189]: checkRange(5500)
Out[189]: 10000

In [190]: checkRange(24872)
Out[190]: 30000

Since you have continuous, sorted ranges, a quicker and less verbose way to do this, is to use the bisect module to find the index in a list of breakpoints and then use it to get the corresponding value from a list of values:

import bisect

break_points = [5499,  9499, 14499, 19499, 24499, 29499, 34499, 39499, 44499]
values       = [5000, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000]

n = 10000
index = bisect.bisect_left(break_points, n)

values[index]
# 15000

You'll need to test for n values that exceed the last breakpoint if that's a possibility. Alternatively you can add a default value to the end of the values list.