溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python中布爾表達(dá)式怎么用

發(fā)布時(shí)間:2021-10-27 17:31:33 來源:億速云 閱讀:284 作者:小新 欄目:編程語言

小編給大家分享一下Python中布爾表達(dá)式怎么用,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

1、布爾表達(dá)式的概念

條件語句和循環(huán)語句都使用布爾表達(dá)式作為條件。布爾值為真或假,以FalseTrue表示,前面經(jīng)常使用布爾表達(dá)式比較兩個(gè)值,如:while x>=0 

2、邏輯問題演示

True and True

False and True

1 == 1 and 2 == 1

"test" == "test"

1 == 1 or 2 != 1

True and 1 == 1

False and 0 != 0

True or 1 == 1

"test" == "testing"

1 != 0 and 2 == 1

"test" != "testing"

"test" == 1

not (True and False)

not (1 == 1 and 0 != 1)

not (10 == 1 or 1000 == 1000)

not (1 != 10 or 3 == 4)

not ("testing" == "testing" and "Zed" == "Cool Guy")

1 == 1 and (not ("testing" == 1 or 1 == 0))

"chunky" == "bacon" and (not (3 == 4 or 3 == 3))

3 == 3 and (not ("testing" == "testing" or "Python" == "Fun"))

所有的布爾邏輯表達(dá)式都可以用下面的簡單流程得到結(jié)果:

1)找到相等判斷的部分 ( == 或者 != ),將其改寫為其最終值 ( True False )。

2)找到括號(hào)里的 and/or ,先算出它們的值。

3)找到每一個(gè) not ,算出他們反過來的值。

4)找到剩下的 and/or ,解出它們的值。

5)等你都做完后,剩下的結(jié)果應(yīng)該就是 True 或者 False 了。

下面我們以20行的邏輯表達(dá)式演示一下:

3 != 4 and not ("testing" != "test" or "Python" == "Python")

接下來你將看到這個(gè)復(fù)雜表達(dá)式是如何逐級(jí)解為一個(gè)單獨(dú)結(jié)果的:

1. > 解出每一個(gè)等值判斷:

> a. 3 != 4 True : True and not ("testing" != "test" or "Python" == "Python") b.

"testing" != "test" True : True and not (True or "Python" == "Python") c.

"Python" == "Python" True : True and not (True or True)

1. > 找到括號(hào)中的每一個(gè) and/or :

> a. (True or True) True: True and not (True)

1. 找到每一個(gè) not 并將其逆轉(zhuǎn):> > a. not (True) False: True and False

1. 找到剩下的 and/or ,解出它們的值:> > a. True and False False

這樣我們就解出了它最終的值為 False.

3、理清復(fù)雜邏輯的技巧

這里告訴大家一條捷徑去判斷布爾表達(dá)式的值。任何的 and 表達(dá)式包含一個(gè) False 結(jié)果就是 False ,任何 or 表達(dá)式有一個(gè) True 結(jié)果就是 True ,你就可以在此處得到結(jié)果,但要確保你能處理整個(gè)表達(dá)式,因?yàn)楹竺孢@是一個(gè)很有用的技能。

以上是“Python中布爾表達(dá)式怎么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI