Ren*_*eno 1 python if-statement return python-2.7
我无法理解我在Python中看到的一些简写符号.有人能够解释这两个功能之间的区别吗?谢谢.
def test1():
first = "David"
last = "Smith"
if first and last:
print last
def test2():
first = "David"
last = "Smith"
print first and last
Run Code Online (Sandbox Code Playgroud)
第一个函数总是返回None(打印Smith)而第二个函数总是返回"Smith"*
快速离题and:
python and运算符返回它遇到的第一个"falsy"值.如果它没有遇到"falsy"值,那么它返回最后一个值(即"true-y")这解释了原因:
"David" and "Smith"
Run Code Online (Sandbox Code Playgroud)
总是回来"Smith".由于两者都是非空字符串,因此它们都是"true-y"值.
"" and "Smith"
Run Code Online (Sandbox Code Playgroud)
会回来,""因为它是一个虚假的价值.
*OP发布的原始功能实际上如下:
def test2():
first = "David"
last = "Smith"
return first and last
Run Code Online (Sandbox Code Playgroud)