我无法理解我在 Python 中看到的一些速记符号。有人可以解释这两个功能之间的区别吗? 谢谢。
def test1():
first = "David"
last = "Smith"
if first and last:
print last
def test2():
first = "David"
last = "Smith"
print first and last
请您参考如下方法:
第一个函数总是返回None(打印Smith)而第二个函数总是返回"Smith"*
快速进入和:
python and 运算符返回它遇到的第一个“falsy”值。如果它没有遇到“falsy”值,则返回最后一个值(即“true-y”)这解释了原因:
"David" and "Smith"
总是返回 "Smith"。由于两者都是非空字符串,因此它们都是“true-y”值。
"" and "Smith"
将返回 "",因为它是一个虚假值。
*OP 发布的原始功能实际上是这样的:
def test2():
first = "David"
last = "Smith"
return first and last
