溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python3中怎么實現(xiàn)真值測試

發(fā)布時間:2021-06-17 14:58:50 來源:億速云 閱讀:241 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細講解有關(guān)python3中怎么實現(xiàn)真值測試,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

1. 真值測試

所謂真值測試,是指當一種類型對象出現(xiàn)在if或者while條件語句中時,對象值表現(xiàn)為True或者False。弄清楚各種情況下的真值對我們編寫程序有重要的意義。

對于一個對象a,其真值定義為:

  • True : 如果函數(shù)truth_test(a)返回True。

  • False:如果函數(shù)truth_test(a)返回False。

以if為例(while是等價的,不做贅述),定義函數(shù)truth_test(x)為:

def truth_test(x):
  if x:
    return True
  else:
    return False

2.對象的真值測試

一般而言,對于一個對象,在滿足以下條件之一時,真值測試為False;否則真值測試為True。

  • 其內(nèi)置函數(shù)__bool__()返回False

  • 其內(nèi)置函數(shù)__len__()返回0

(1)以下類型對象真值測試為真:

class X:
   pass

(2)以下真值測試為假:

class Y:
   def __bool__(self):
     return False

(3)以下真值測試為假:

class Z:
   def __len__(self):
     return 0

進入python3腳本環(huán)境,測試過程如下:

>>> class X:
...   pass
... 
>>> class Y:
...   def __bool__(self):
...     return False
... 
>>> class Z:
...   def __len__(self):
...     return 0
... 
>>> def truth_test(x):
...   if x:
...     return True
...   else:
...     return False
... 
>>> x = X()
>>> y = Y()
>>> z = Z()
>>> truth_test(x)
True
>>> truth_test(y)
False
>>> truth_test(z)
False
>>>

3. 常見對象的真值

下面是常見的真值為False的情況:

  • 常量:None and False.

  • 數(shù)值0值: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)

  • 序列或者集合為空:'', (), [], {}, set(), range(0)

進入python3腳本環(huán)境,測試過程如下:

>>> truth_test(None)
False
>>> truth_test(False)
False
>>> truth_test(0)
False
>>> truth_test(0.0)
False
>>> truth_test(0j)  #復(fù)數(shù)
False
>>> truth_test(Decimal(0)) #十進制浮點數(shù)
False
>>> truth_test(Fraction(0,1)) #分數(shù)
False
>>> truth_test(Fraction(0,2)) #分數(shù)
False
>>> truth_test('')
False
>>> truth_test(())
False
>>> truth_test({})
False
>>> truth_test(set())
False
>>> truth_test(range(0)) #序列
False
>>> truth_test(range(2,2)) #序列
False

此外的其它取值,真值測試應(yīng)當為True。

4.一些有意思的例子

下面是一些有意思的例子,原理不超出前面的解釋。

>>> if 1 and Fraction(0,1):
...   print(True)
... else:
...   print(False)
... 
False
>>> if 1 and ():
...   print(True)
... else:
...   print(False)
... 
False
>>> if 1 and range(0):
...   print(True)
... else:
...   print(False)
... 
False
>>> if 1 and None:
...   print(True)
... else:
...   print(False)
... 
False
>>> if 1+2j and None:
...   print(True)
... else:
...   print(False)
... 
False

關(guān)于python3中怎么實現(xiàn)真值測試就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI