据我所知,比较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。为什么呢?
答案 0 :(得分:3)
您正在见证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!
答案 1 :(得分:0)
如果仔细检查代码,您会注意到您将最大值初始化为dist
,然后有条件地询问它是否为None
,因此if语句的计算结果为None
。< / p>