Python的邏輯操作有三種:and、or、not。分別對應與、或、非。舉例:
Python的邏輯操作有三種:and、or、not。分別對應與、或、非。
舉例:
1 #coding:utf-8
2 test1 = 12
3 test2 = 0
4 print (test1 > test2) and (test1 > 14) #result = False
5 print (test1 < test2) or (test1 > -1) #result = True
6 print (not test1) #result = False
7 print (not test2) #result = True
嚴格的說,邏輯操作符的運算元應該為布林運算式。但Python對此處理的比較靈活。即使運算元是數字,解譯器也把他們當成“運算式”。非0的數位布爾值為1,0的布爾值為0.舉例:
1 #coding:utf-8
2 test1 = 12
3 test2 = 0
4 print (test1 and test2) #result = 0
5 print (test1 or test2) #result = 12
6 print (not test1) #result = Flase
7 print (not test2) #reslut = True
在Python中,Null 字元串為假,非Null 字元串為真。非零的數為真。數字和字串之間、字串之間的邏輯操作規律是:對於and操作符:只要左邊的運算式為真,整個運算式返回的值是右邊運算式的值,否則,返回左邊運算式的值對於or操作符:只要兩邊的運算式為真,整個運算式的結果是左邊運算式的值。如果是一真一假,返回真值運算式的值如果兩個都是假,比如空值和0,返回的是右邊的值。(空值或0)舉例:
1 #coding:utf-8
2 test1 = 12
3 test2 = 0
4 test3 = ''
5 test4 = "First"
6 print test1 and test3 #result = ''
7 print test3 and test1 #result = ''
8 print test1 and test4 #result = "First"
9 print test4 and test1 #result = 12
10 print test1 or test2 #result = 12
11 print test1 or test3 #result = 12
12 print test3 or test4 #result = "First"
13 print test2 or test4 #result = "First"
14 print test1 or test4 #result = 12
15 print test4 or test1 #result = "First"
16 print test2 or test3 #result = ''
17 print test3 or test2 #result = 0
{網購拿返利,購物新選擇}