首页 > 解决方案 > “无”不能与数字相比较。还有其他选择吗?

问题描述

在 Python 2 中,您可以将 None 与解决方案中的整数和浮点数进行比较,以通过比较找到最小的数。但在 Python 3 中,它们无法进行比较。您在 Python 3 中有任何替代关键字或解决方案吗?

TypeError: '>' not supported between instances of 'int' and 'NoneType'

这是我的代码:

l = None
s = None

while True:
    n = input("Enter a number: ")
    if (n == "done") :
        break
    try:
        num = int(n)
    except:
        print ("Invalid input")
        continue
    if (s is None):
        s = num
    if (num > l) :
        l = num
    elif (num < s) :
        s = num

def done(l,s):
    print ("Maximum is", l)
    print ("Minimum is", s)

done(l,s)

标签: pythonpython-3.xnumbersintnonetype

解决方案


由于None在 Python 2 中有效地充当负无穷大[*],您可以使用 (代替x < y)

False if y is None else True if x is None else x < y

我们y首先检查结果是False当两者时xyNone

>>> def f(x, y):
...   return False if y is None else True if x is None else x < y
...
>>> f(None, None)
False
>>> f(None, -10000)
True
>>> f(-10000, None)
False

如果你要定义一个函数,你应该使用if语句来编写它以清楚起见,但是:

def f(x, y):
    if y is None:
        return False
    if x is None:
        return True
    return x < y

[*] 更准确地说,None充当 . 所暗示的格子的底部<=


推荐阅读