简体   繁体   English

Python-将数字与布尔值比较(总是返回false)

[英]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? 在Python中是否存在某种可以在逻辑上进行比较以始终为false的关键字?

For example, I want something like 例如,我想要类似

None > 20

To return false when evaluated. 在评估时返回false。 Is there some keyword to use besides None here, since comparing a NoneType and Integer throws an error? 由于在比较NoneType和Integer时会抛出错误,因此这里除了None之外,还需要使用其他一些关键字吗?

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 > 20返回False,而不特别关心其他比较返回的结果,则使用特殊的“负无穷大”浮点值可能更有意义。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM