gpt4 book ai didi

python - 在 Python3 中比较 int 和 None 没有 TypeError

转载 作者:太空宇宙 更新时间:2023-11-04 00:30:34 24 4
gpt4 key购买 nike

我明白在 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 运行此脚本时,它运行时没有类型错误。为什么?

最佳答案

您正在目睹短路

if largest is None or number > largest:
(1) or (2)

当条件 (1) 被评估为真时,条件 (2) 被执行。在第一次迭代中,largest is NoneTrue,因此整个表达式为真。


作为一个说明性示例,请考虑这个小片段。

test = 1
if test or not print('Nope!'):
pass

# Nothing printed

现在,用 test=None 重复:

test = None
if test or not print('Nope!'):
pass

Nope!

关于python - 在 Python3 中比较 int 和 None 没有 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45973628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com