剛開始看python,覺得這個邏輯操作符和其他語言有些區別,所以就記錄下來。
Python的邏輯操作有三種:and、or、not。分別對應與、或、非。
嚴格的說,邏輯操作符的運算元應該為布林運算式。但Python對此處理的比較靈活。
即使運算元是數字,解譯器也把他們當成“運算式”。
非0的數位布爾值為1,0的布爾值為0.
在Python中,Null 字元串為假,非Null 字元串為真。非零的數為真。
對於and操作符a and b:
只要左邊的運算式為真,整個運算式返回的值是右邊運算式的值,否則,返回左邊運算式的值
對於or操作符 a or b:
只要左邊的運算式為真,整個運算式返回的值是左邊運算式的值,否則,返回右邊運算式的值
對於not操作符 not a:
如果 a 為 True,返回 False 。如果 a 為 False,它返回 True。
舉例:
假設變數 a 為 10, b為 20
(a and b) 返回 20。
(a or b) 返回 10。
not(a and b) 返回 False
#coding:utf-8 test1 = 12 test2 = 0 test3 = '' test4 = "First" print test1 and test3 #result = '' print test3 and test1 #result = '' print test1 and test4 #result = "First" print test4 and test1 #result = 12 print test1 or test2 #result = 12 print test1 or test3 #result = 12 print test3 or test4 #result = "First" print test2 or test4 #result = "First" print test1 or test4 #result = 12 print test4 or test1 #result = "First" print test2 or test3 #result = '' print test3 or test2 #result = 0