python - “无”不能与数字相比较。还有其他选择吗?
问题描述
在 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)
解决方案
由于None
在 Python 2 中有效地充当负无穷大[*],您可以使用 (代替x < y
)
False if y is None else True if x is None else x < y
我们y
首先检查结果是False
当两者时x
和y
是None
:
>>> 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
充当 . 所暗示的格子的底部<=
。
推荐阅读
- sql - 复杂的日期连接:需要每个组的最近日期条目出现在另一个表的日期条目之前
- excel - Range类的PasteSpecial方法复制后失败
- python - 为什么像这样索引图片的ndarray会使图片变成绿色和蓝色?
- python - PyCharm 找不到 queue.SimpleQueue
- vulkan - 如何使用 Vulkan 时间戳查询?
- sql-server - 无法从链接服务器插入带有标识列的表
- reactjs - 使用动态道具反应顶级模态
- r - R中的make.unique中的括号
- python - 如何使用带有 str.format() 的自记录等于(调试)说明符?
- python - 打印特殊字符