Chained comparison number range in Python

williamtroup picture williamtroup · Nov 12, 2013 · Viewed 9.2k times · Source

I have the following function:

def InRange(number):
    return 5 <= number >= 1

I want this to say false if the number is not within the range of 1 to 5 using a chain comparison, but cannot seem to get this right.

Any suggestions?

Answer

user2555451 picture user2555451 · Nov 12, 2013

You want it like this:

def InRange(number):
    return 1 <= number <= 5

Note that you could also do:

def InRange(number):
    return 0 < number < 6