为什么我可以通过"if largest is None or largest < num:"而不是"if largest < num:"



当我试图通过"但不是";如果最大<num:";我得到了";类型错误:'<'在"NoneType"one_answers"int"的实例之间不支持;。这意味着我无法比较NoneType和整数。但";如果最大值为None或最大<num:"?

largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
num = int(num)  
if largest is None or largest < num:
largest = num
if smallest is None or smallest > num:
smallest = num 
except:
print("Invalid input")
continue
print("Maximum is", largest)
print("Minimum is", smallest)

为了解释,这里有一个例子:

if True or (1 < None):
print('yep')
if 1 < None:
print('this does not print, because the above throws an exception')

先打印yep,然后打印TypeError: '<' not supported between instances of 'int' and 'NoneType'

正如@shadowranger在评论中指出的那样,发生这种情况的原因是像orand这样的逻辑运算符短路。

对于or,这意味着在计算P or Q时,如果P的计算结果为True,则无需计算Q,因为不管怎样,表达式都将是True,因此Python不会。

类似地,对于and,这意味着在计算P and Q时,如果P的计算结果为False,则无需计算Q,因为不管怎样,表达式都将是False,因此Python不会。

所以,你可以看到为什么这不会引发异常,因为违规代码永远不会被执行:

if True or (1 < None):
print('yep')

最新更新