Python邏輯操作中的三大應(yīng)用方案
Python邏輯在運(yùn)作中有不少的問題需要解決。下面我們就詳細(xì)的看看如何進(jìn)行實(shí)際的操作。在實(shí)際的使用中有三種:and、or、not。分別對(duì)應(yīng)與、或、非。希望大家有所收獲。
舉例:
- #coding:utf-8
- test1 = 12
- test2 = 0
- print (test1 > test2) and (test1 > 14) #result = False
- print (test1 < test2) or (test1 > -1) #result = True
- print (not test1) #result = False
- print (not test2) #result = True
嚴(yán)格的說,邏輯操作符的操作數(shù)應(yīng)該為布爾表達(dá)式。但Python邏輯操作對(duì)此處理的比較靈活。即使操作數(shù)是數(shù)字,解釋器也把他們當(dāng)成“表達(dá)式”。非0的數(shù)字的布爾值為1,0的布爾值為0.
舉例:
- #coding:utf-8
- test1 = 12
- test2 = 0
- print (test1 and test2) #result = 0
- print (test1 or test2) #result = 12
- print (not test1) #result = Flase
- print (not test2) #reslut = True
在Python邏輯操作中,空字符串為假,非空字符串為真。非零的數(shù)為真。
數(shù)字和字符串之間、字符串之間的邏輯操作規(guī)律是:
對(duì)于and操作符:只要左邊的表達(dá)式為真,整個(gè)表達(dá)式返回的值是右邊表達(dá)式的值,否則,返回左邊表達(dá)式的值對(duì)于or操作符:只要兩邊的表達(dá)式為真,整個(gè)表達(dá)式的結(jié)果是左邊表達(dá)式的值。
如果是一真一假,返回真值表達(dá)式的值,如果兩個(gè)都是假,比如空值和0,返回的是右邊的值。(空值或0)舉例:
- #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 = 1212 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
以上就是對(duì)Python邏輯的相關(guān)的介紹。
【編輯推薦】



















