johnsmith101
johnsmith101

Reputation: 189

Python - Compare number with boolean (always return false)

Is there some kind of keyword to use in Python, that can be logically compared to always be false?

For example, I want something like

None > 20

To return false when evaluated. Is there some keyword to use besides None here, since comparing a NoneType and Integer throws an error?

Upvotes: 1

Views: 1249

Answers (1)

Kevin
Kevin

Reputation: 76234

I don't think there's a built-in object that does this, but you can always make your own:

class Thing:
    def __lt__(self, other):
        return False
    #use the same function for <=, ==, >, etc
    __le__ = __eq__ = __gt__ = __ge__ = __lt__

x = Thing()
print(x < 20)
print(x <= 20)
print(x > 20)
print(x >= 20)
print(x == 20)

Result:

False
False
False
False
False

Edit: I remembered a built-in way to do this. If you only need to compare to ordinary numbers, you can use the special "Not a Number" floating point value:

x = float("nan")
print(x < 20)
print(x <= 20)
print(x > 20)
print(x >= 20)
print(x == 20)

Result:

False
False
False
False
False

And if you specifically only want x > 20 to return False and don't particularly care what the other comparisons return, it may make more sense to use the special "negative infinity" floating point value.

>>> x = float("-inf")
>>> x > 20
False

Upvotes: 6

Related Questions