我无法理解我在 Python 中看到的一些简写符号。请问有人可以解释这两个功能之间的区别吗?谢谢你。
def test1():
first = "David"
last = "Smith"
if first and last:
print last
def test2():
first = "David"
last = "Smith"
print first and last
我无法理解我在 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"
*
快速题外话and
:
pythonand
运算符返回它遇到的第一个“假”值。如果它没有遇到“假”值,则返回最后一个值(即“true-y”)这解释了原因:
"David" and "Smith"
总是返回"Smith"
。由于两者都是非空字符串,它们都是“真-y”值。
"" and "Smith"
会返回""
,因为它是一个虚假值。
* OP 发布的原始函数实际上是这样的:
def test2():
first = "David"
last = "Smith"
return first and last
test1()
函数和之间的区别在于,只要表达式的结果为真,就会显式打印 的值,并test2()
打印test1()
表达式的结果。打印的字符串是相同的,因为表达式的结果是 - 的值,但仅仅是因为计算结果为真。last
first and last
test2()
first and last
first and last
last
first
在 Python 中,如果表达式的左侧and
计算结果为真,则表达式的结果是该表达式的右侧。由于布尔运算符的短路,如果and
表达式的左侧计算为假,则返回表达式的左侧。
or
在 Python 中也会短路,返回表达式最左边的值,它决定了整个表达式的真值。
所以,看看更多的测试功能:
def test3():
first = ""
last = "Smith"
if first and last:
print last
def test4():
first = ""
last = "Smith"
print first and last
def test5():
first = "David"
last = "Smith"
if first or last:
print last
def test6():
first = "David"
last = "Smith"
print first or last
def test7():
first = "David"
last = ""
if first or last:
print last
def test8():
first = "David"
last = ""
print first or last
test3()
不会打印任何东西。
test4()
将打印""
。
test5()
将打印"Smith"
。
test6()
将打印"David"
。
test7()
将打印""
。
test8()
将打印"David"
。
你问,这两个片段之间有什么区别?
if first and last:
print last
和
print first and last
在第一种情况下,代码要么打印 last 的值,要么不打印。
在第二种情况下,代码将打印 的值first and last
。如果您习惯于 C,那么您可能会认为 的值a and b
是布尔值 True 或 False。但你错了。
a and b
评估a
;如果a
为真,则表达式的值为b
。如果a
是错误的,则表达式的值为a
:
"David" and "Smith" -> "Smith"
0 and "Smith" -> 0
1 and "Smith" -> "Smith"
"David" and 0 -> 0
"David" and 1 -> 1
一般来说:
last
,如果它打印任何东西
first
要么。last
first
具体来说,如果first
is ever ""
,则第二个示例将打印""
,而第一个示例根本不会打印任何内容。