[英]What is the difference between these two python functions?
我無法理解我在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
:
python and
運算符返回它遇到的第一個“ falsy”值。 如果沒有遇到“假”值,那么它將返回最后一個值(即“ true-y”),這說明了原因:
"David" and "Smith"
總是返回"Smith"
。 由於兩者都是非空字符串,因此它們都是“ true-y”值。
"" and "Smith"
會返回""
因為它是偽造的值。
* OP發布的原始功能實際上是這樣的:
def test2():
first = "David"
last = "Smith"
return first and last
函數test1()
和test2()
之間的區別在於,只要表達式first and last
的結果為true,則test1()
顯式打印出last
的值,而test2()
則first and last
打印表達式的結果, first and last
。 被打印的字符串是相同,因為表達式的結果first and last
是的值last
-但僅僅是因為first
評估為真。
在Python中,如果and
表達式的左側求值為true,則表達式的結果為該表達式的右側。 由於布爾運算符的短路,如果and
表達式的左側求值為false,則返回該表達式的左側。
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
的真實性印刷first
或last
。 具體來說,如果first
曾經是""
,那么第二個示例將打印""
而第一個示例根本不打印任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.