簡體   English   中英

這兩個python函數有什么區別?

[英]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 ba ; 如果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的真實性印刷firstlast

具體來說,如果first曾經是"" ,那么第二個示例將打印""而第一個示例根本不打印任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM