- 真值測試
所謂真值測試,是指當一種類型對象出現在if或者while條件語句中時,對象值表現爲True或者False。弄清楚各種情況下的真值對我們編寫程序有重要的意義。
對於一個對象a,其真值定義爲:
True : 如果函數truth_test(a)返回True。
False:如果函數truth_test(a)返回False。
以if爲例(while是等價的,不做贅述),定義函數truth_test(x)爲:
def truth_test(x):
if x:
return True
else:
return False
2.對象的真值測試
一般而言,對於一個對象,在滿足以下條件之一時,真值測試爲False;否則真值測試爲True。
其內置函數bool()返回False
其內置函數len()返回0
(1)以下類型對象真值測試爲真:
class X:
pass
(2)以下真值測試爲假:
class Y:
def bool(self):
return False
(3)以下真值測試爲假:
class Z:
def len(self):
return 0
進入python3腳本環境,測試過程如下:
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
- 常見對象的真值
下面是常見的真值爲False的情況:
常量:None and False.
數值0值: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
序列或者集合爲空:”, (), [], {}, set(), range(0)
進入python3腳本環境,測試過程如下:
truth_test(None)
False
truth_test(False)
False
truth_test(0)
False
truth_test(0.0)
False
truth_test(0j) #複數
False
truth_test(Decimal(0)) #十進制浮點數
False
truth_test(Fraction(0,1)) #分數
False
truth_test(Fraction(0,2)) #分數
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
此外的其它取值,真值測試應當爲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