我很難理解我在Python中看到的一些簡寫符號。有人能夠解釋這兩個功能之間的區別嗎? 謝謝。這兩個python函數有什麼區別?
def test1():
first = "David"
last = "Smith"
if first and last:
print last
def test2():
first = "David"
last = "Smith"
print first and last
我很難理解我在Python中看到的一些簡寫符號。有人能夠解釋這兩個功能之間的區別嗎? 謝謝。這兩個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
:
蟒and
運算符返回第一 「falsy」它遇到的價值。如果沒有遇到「falsy」值,則返回最後一個值(這是「真-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
評估爲true,test2()
打印表達式first and last
的結果。被打印的字符串是相同的,因爲表達first and last
的結果是last
值 - 但僅僅是因爲first
評估爲真。
在Python,如果and
表達式的左側評估爲真,則表達式的結果是,表達的右手側。由於布爾運算符的短路,如果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"
。
+1以簡短地解釋短路。這讓我在本週早些時候感到困惑,但我發現這個[wikibooks]鏈接非常有幫助。 – 2013-04-11 18:28:48
編輯我的回覆以響應更正的問題。 – pcurry 2013-04-12 03:39:36
你問,這兩個片段之間的區別是什麼?
if first and last:
print last
和
print first and 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
Generallly:
last
,如果它打印在所有
first
或last
什麼,根據first
的感實性。特別是,如果first
是有史以來""
,然後第二個例子將打印""
而 第一將不打印任何東西。
@DSM - 是的。出於某種原因,我把它看作是一個'或'。 – mgilson 2013-04-11 15:18:43
感謝您的幫助。對不起,我實際上打算爲這兩種功能寫「打印」,而不是打印一份,然後返回另一份。這是一個錯字。我已經糾正了上述問題。這兩個功能現在是否基本相同?謝謝。 – Reno 2013-04-11 15:27:06
@Reno - 他們是一樣的,因爲'first'和'last'都是'true-like'值。如果情況並非如此 - (例如,如果「first」和「last」是該函數的參數),它們可能仍然不同。 – mgilson 2013-04-11 15:28:46