在Python中,不單單和類C同樣的真假相似,好比1表明真,0表明假。Python中的真假有着更加廣闊的含義範圍,Python會把全部的空數據結構視爲假,好比[]
(空列表)、{}
(空集合)、''
(空字符串)等,而與之相反的非空數據結構即爲真python
# 遍歷列表中的示例元素,獲取對應的真假: for elenment in ['', 'S', [], [1, 2], {}, {3, 'SSS'}, 0, 0.0, 1, None]: if elenment: print(elenment, True) else: print(elenment, False)
False S True [] False [1, 2] True {} False {'SSS', 3} True 0 False 0.0 False 1 True None False
在Python中None不單單表明False,它自己就是一個特殊的空對象,能夠用來佔位,好比咱們能夠利用None實現相似C中定義數組的方式,預約義列表的大小,實現對可能的索引進行賦值,而爲賦值的索引都爲None叉車配件數組
L = [None] * 10 print(L)
空列表定義結果數據結構
[None, None, None, None, None, None, None, None, None, None]
在Python中布爾值,True和False不單單能夠表示真與假,甚至能夠用於數學運算:ui
print(True+1) print(False+1) print(True+False)
運算結果spa
2 1 1
即True爲1,False爲0,爲什麼Python中布爾值能夠進行數學運算? 咱們能夠利用isinstance
驗證其是否爲整型:code
print(isinstance(True, int)) print(isinstance(False, int))
驗證結果:對象
True True
即實質上在Python中布爾值自己是整型(int),即bool類型就是int類型的子類。索引