簡體   English   中英

Python'和'可以返回無?

[英]can Python 'and' return None?

我正在查看一些顯然運行的代碼,因為沒有人抱怨它,但我對它們所寫的內容感到困惑:

if a and b is not None:
    # do something

我一直認為'和'運算符是返回True或False的東西,現在我開始懷疑自己..它還會返回什么,一個數字......它可能不是pythonic,但我錯過了什么 - 怎么能有人寫這樣的東西?

這意味着如果a is Truthyb is not None而不是你認為它意味着a and b is Truthy

a = 999
b = None

if a and b is not None:
    print("a is True but b is None")
else:
    print("a is True and b is not None")

上面的代碼意味着:

如果a (是真的),AND b不是None ,那么#do something

根據[Python 3]:運算符優先級強調是我的):

下表總結了Python中的運算符優先級, 從最低優先級(最小綁定)到最高優先級(大多數綁定)

 ... and Boolean AND not x Boolean NOT in, not in, is, is not, <, <=, >, >=, !=, == Comparisons, including membership tests and identity tests ... 

事實並非如此 並且意味着它將在之前進行評估並且 (由於懶惰的評估 ,可能根本不進行評估 - 感謝@NickA的評論),因此表達式相當於(為了清晰起見,添加了括號) ):

if a and (b is not None):

另外,根據[Python 3]:真值測試

可以測試任何對象的真值,用於ifwhile條件或下面的布爾運算的操作數。

你的if語句是完全OK(產生布爾 )。

示例(使用[Python 3]:類bool[x] ):

 >>> bool(0) False >>> bool(100) True >>> bool([]) False >>> bool([0]) True >>> bool(None) False >>> bool({}) False >>> bool({1: 1}) True >>> bool(None is not None) False >>> bool(1 is not None) True >>> bool(2 and 1 is not None) True 

在此代碼中,您首先評估b is not None ,這是一個布爾值。

然后a被隱式轉換為布爾型(對於list / dictFalse如果它是空的。對於許多, False如果它是0)

然后and評價總是返回一個布爾值。

這當然是有效的。

當我們采取已經分配的值,並且與另一可變用空執行AND操作(在python -沒有)的變量,該AND運算結果 因此,可以進行檢查。 為了清楚說明,請參閱下文。

a=2;c=None; b=11
if a and c is not None:
    print("T")
else:
    print("F")

print(a and c)

結果為

print(a and b)

結果為非空值 - 在我們的例子中為11

暫無
暫無

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

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