首页 > 解决方案 > 关于 Python 中的逻辑与的混淆

问题描述

以下是 Python 中的玩具示例:

a = 2
b= 10
result = a<b and print("Hello")
print(bool(result))

输出是:

Hello
False

为什么是输出False而不是True?由于result评估为a<b= 2<10 = Truethen,我们有result = True and print()= True and True= True。有人可以解释这个答案的原因吗?

标签: pythonoperatorsboolean-logic

解决方案


print返回None

>>> print("Hello") is None
True

并且None是一个Falsey 值:

>>> bool(None)
False

所以你有True and False,评估为False


推荐阅读