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

Viewed 89
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 ?

2 Answers

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

Just rewrite your if to a single line with else:

def RangeChecker(num):
    return True if num in range(1000, 100001) else False
Related