Python 布爾類型 bool
python 中布爾值使用常量True 和 False來表示;注意大小寫
比較運算符< > == 等返回的類型就是bool類型;布爾類型通常在 if 和 while 語句中應用
這邊需要注意的是,python中,bool是int的子類(繼承int),故 True==1 ?False==0 是會返回Ture的,有點坑,如要切實判斷用 xxx is True
1 print(True==1) # 返回True 2 print(False==0) # 返回True 3 print(1 is True) 4 print(0 is False)
另外,還有幾個坑。。。 如,Python2中True/False不是關鍵字,因此我們可以對其進行任意的賦值;同理,Python 中 if(True) 的效率遠比不上 if(1)
? True =?"True is not keyword in Python2"? ? ? ??#?Python2 版本中True False不是關鍵字,可被賦值,Python3中會報錯?
另,由于bool是int,可進行數字計算?? print(True+True)?
?
True or False 判定
以下會被判定為 False?:
- None
- False
- zero of any numeric type, for example, 0, 0.0, 0j.
- any empty sequence, for example, '', (), [].
- any empty mapping, for example, {}.
- instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False.
除了以上的,其他的表達式均會被判定為 True,這個需要注意,與其他的語言有比較大的不同。
1 print(bool()) 2 print(bool(False)) 3 print(bool(0),bool(0.0),bool(0j)) 4 print(bool(""),bool(()),bool([]),bool({})) 5 class alfalse(): 6 def __bool__(self): # 定義了 __bool__() 方法,始終返回False 7 return False 8 f = alfalse() 9 print(bool(f)) 10 class alzero(): 11 def __len__(self): # 定義了 __len__() 方法,始終返回0 12 return 0 13 zero = alzero() 14 print(bool(zero)) 15 class justaclass(): 16 pass 17 c = justaclass() 18 print(bool(c)) # 一般class instance都返回為True
?
布爾運算符 and ? or ? not
?
Operation | Result |
---|---|
x? or? y | if? x ?is false, then? y , else? x |
x? and? y | if? x ?is false, then? x , else? y |
not? x | if? x ?is false, then? True , else? False |
?
注意均為小寫: and or not ?; ?注意布爾運算的優先級低于表達式,?not a == b 相當于 not (a == b), 若 a == not b 就會有語法錯誤
轉載自:https://www.cnblogs.com/feeland/p/4360331.html
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
