国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

詳解python3中的真值測試

2020-02-15 22:44:33
字體:
來源:轉載
供稿:網友

1. 真值測試

所謂真值測試,是指當一種類型對象出現在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>>>

3. 常見對象的真值

下面是常見的真值為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            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 永春县| 赞皇县| 诏安县| 长顺县| 十堰市| 同江市| 景德镇市| 龙里县| 新沂市| 右玉县| 仁布县| 营山县| 汽车| 漳州市| 交口县| 万山特区| 兴义市| 巴青县| 元谋县| 牟定县| 德化县| 东乌| 彩票| 常德市| 德格县| 邹城市| 屏南县| 承德县| 万山特区| 龙胜| 翁牛特旗| 尚志市| 慈利县| 福泉市| 顺昌县| 山东省| 郴州市| 玉树县| 大同市| 萨迦县| 吴堡县|