您好,登錄后才能下訂單哦!
這篇文章給大家介紹Python邏輯操作中的三大應(yīng)用方案,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
Python邏輯在運(yùn)作中有不少的問(wèn)題需要解決。在實(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)格的說(shuō),邏輯操作符的操作數(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
關(guān)于Python邏輯操作中的三大應(yīng)用方案就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。