我知道在Python3(3.6.1(中比较int和None类型是无效的,正如我在这里看到的:
>>> 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
,因此整个表达式为真。
作为一个示例,请考虑这个小片段。
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
。