在Python編程的學習中,布爾邏輯可以說是無處不在。布爾表達式是計算機運算的基礎和重要組成部分,掌握它們就跟學音樂要掌握音階一樣有必要。今天本文將帶大家一起來學習布爾表達式,主要內容有布爾表達式的概念、邏輯問題演示以及理清復雜邏輯的技巧。

1、布爾表達式的概念
條件語句和循環語句都使用布爾表達式作為條件。布爾值為真或假,以False和True表示,前面經常使用布爾表達式比較兩個值,如: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"))
所有的布爾邏輯表達式都可以用下面的簡單流程得到結果:
(1)找到相等判斷的部分 ( == 或者 != ),將其改寫為其最終值 ( True 或 False )。
(2)找到括號里的 and/or ,先算出它們的值。
(3)找到每一個 not ,算出他們反過來的值。
(4)找到剩下的 and/or ,解出它們的值。
(5)等你都做完后,剩下的結果應該就是 True 或者 False 了。
下面我們以20行的邏輯表達式演示一下:
3 != 4 and not ("testing" != "test" or "Python" == "Python")
接下來你將看到這個復雜表達式是如何逐級解為一個單獨結果的:
1. > 解出每一個等值判斷:
> 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. > 找到括號中的每一個 and/or :
> a. (True or True) 為 True: True and not (True)
1. 找到每一個 not 並將其逆轉:> > a. not (True) 為 False: True and False
1. 找到剩下的 and/or ,解出它們的值:> > a. True and False 為 False
這樣我們就解出了它最終的值為 False.
3、理清復雜邏輯的技巧
這里告訴大家一條捷徑去判斷布爾表達式的值。任何的 and 表達式包含一個 False 結果就是 False ,任何 or 表達式有一個 True 結果就是 True ,你就可以在此處得到結果,但要確保你能處理整個表達式,因為后面這是一個很有用的技能。
在Python基礎學習的過程中,布爾表達式可能會讓初學者感覺到復雜和困難。但是只要通過更多的相關練習,相信大家可以很快理解布爾表達式並熟練運用它。即便是現在暫時的不理解也沒關系,只要你堅持下去了,量變終會影響質變!