Python - Compare number with boolean (always return false)

johnsmith101

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?

Kevin

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Boolean Function Always Return False

Boolean values return false always

Comparing number always return false

Java Boolean method return is always false

bcrypt.compare with Promise always return false

Compare password in WordPress always return false

Why casting bool on boolean type return always false

The boolean return statement inside a for loop and if statement is always returning false in java

Python function that always return the same boolean value

bcrypt-nodejs compare function always return false

Cypress-compare file contents with an array always return false

Python isinstance(var, Type) always return False

Always return false in python outright, it is true

Return number of "false" Boolean values from an array - MobX & React

Python code Always returning None boolean when False should be returned

Always returning false as boolean value

.Equals or == return false, always

getCheckedItemPositions always return false

SQL to always return false

Bcrypt compare always returning false

Why directly use dir() in all(...) always return False in python?

Lua: attempt to compare boolean with number

How to compare SQL files and Packages in Python and return True or False?

ArrayFormula boolean AND return a false positive

python - compare string with boolean

Why can't i compare this two string ? The string input is the same, but it always return false

always return false when compare an existing string from a test file to the newly enterer object with parameter

ajax submit always return false

CodeIgniter Emails always return false