我正在查看一些显然可以运行的代码,因为没有人提示过它,但我对他们编写的内容感到很困惑:
if a and b is not None:
# do something
我一直认为“和”运算符是返回 True 或 False 的东西,现在我开始怀疑自己了。它还会返回什么,一个数字。它可能不是 pythonic,但我是否遗漏了什么- 怎么会有人写这样的东西?
最佳答案
这意味着如果 a 是 Truthy
并且 b 不是 None
而不是你认为的意思,即 a 和 b 是 Truthy
a = 999
b = None
if a and b is not None:
print("a is True but b is None")
else:
print("a is True and b is not None")
关于python - Python 'and' 可以返回 None 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54108493/