[英]No TypeError comparing int with None in Python3
我了解比较int和None类型在Python3(3.6.1)中无效,如下所示:
>>> largest = None
>>> number = 5
>>> number > largest
TypeError: '>' not supported between instances of int and NoneType
但是在此脚本中,它没有给出TypeError。
largest = None
for number in [5, 20, 11]:
if largest is None or number > largest:
largest = number
当我使用python3运行此脚本时,它运行时没有TypeError。 为什么?
您正在目睹short circuiting
。
if largest is None or number > largest:
(1) or (2)
当条件(1)
评估为真时, 不执行条件(2)
。 在第一次迭代中, largest is None
为True
,因此整个表达式为true。
作为说明性示例,请考虑以下小片段。
test = 1
if test or not print('Nope!'):
pass
# Nothing printed
现在,重复test=None
:
test = None
if test or not print('Nope!'):
pass
Nope!
如果仔细检查代码,您会注意到将最大的初始化为None
,然后有条件地询问它是否为None
,因此if语句的值为True
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.