Search code examples
pythonpython-3.xfunctionreturnboolean

Define a function in python which returns if the number is in the range say 1,000 to 10,000. But the catch is I have to do it in one line only


def RangeChecker(num):
    if num in range(1000, 10001):
        return True
    return False
x = RangeChecker(500)

This is my code , how do I change the function to a single return statement ?


Solution

  • Simply return the condition itself as it evaluates to the exact boolean value you want to return:

    def RangeChecker(num):
        return num in range(...)
    

    If you want to allow non-integers and understand "range" in a more natural language way, you could go with comparison operator chaining:

    def RangeChecker(num):
        return 1000 <= num <= 10000