上一節(jié)學到的邏輯組合的正式名稱是“布爾邏輯表達式(boolean logic expression)”。在編程中,布爾邏輯可以說是無處不在。它們是計算機運算的基礎和重要組成部分,掌握它們就跟學音樂掌握音階一樣重要。
在這節(jié)練習中,你將在 python 里使用到上節(jié)學到的邏輯表達式。先為下面的每一個邏輯問題寫出你認為的答案,每一題的答案要么為 True 要么為 False。寫完以后,你需要將 python 運行起來,把這些邏輯語句輸入進去,確認你寫的答案是否正確。
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"))
在本節(jié)結尾的地方我會給你一個理清復雜邏輯的技巧。
所有的布爾邏輯表達式都可以用下面的簡單流程得到結果:
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)
2.找到括號中的每一個 and/or:
a. (True or True) 為 True: True and not (True)
3.找到每一個 not 并將其逆轉:
a. not (True) 為 False: True and False
4.找到剩下的 and/or,解出它們的值:
a. True and False 為 False
這樣我們就解出了它最終的值為 False.
Warning: 復雜的邏輯表達式一開始看上去可能會讓你覺得很難。而且你也許已經碰壁過了,不過別灰心,這些“邏輯體操”式的訓練只是讓你逐漸習慣起來,這樣后面你可以輕易應對編程里邊更酷的一些東西。只要你堅持下去,不放過自己做錯的地方就行了。如果你暫時不太能理解也沒關系,弄懂的時候總會到來的。
以下內容是在你自己猜測結果以后,通過和 python 對話得到的結果:
$ python
Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> True and True
True
>>> 1 == 1 and 2 == 2
True
1.Python 里還有很多和!=、 == 類似的操作符. 試著盡可能多地列出 Python 中的等價運算符。例如 < 或者 <= 。 2.寫出每一個等價運算符的名稱。例如 != 叫 “not equal(不等于)”。 3.在 python 中測試新的布爾操作。在敲回車前你需要喊出它的結果。不要思考,憑自己的第一感就可以了。把表達式和結果用筆寫下來再敲回車,最后看自己做對多少,做錯多少。 4.把習題 3 那張紙丟掉,以后你不再需要查詢它了。
python 和很多語言可以返回布爾表達式中的一個操作數,而不僅僅是真或假。這意味著如果你計算 False and 1 你會得到表達式的第一個操作數 (False) ,但是如果你計算 True and 1 的時候,你得到它的第二個操作數(1)。試一試吧。
Python 已經聲明贊成使用!=而棄用<>所以盡量使用!=吧。其他的應該沒有區(qū)別了。
有的。任何的 and 表達式包含一個 False 結果就是 False,任何 or 表達式有一個 True 結果就是 True,你就可以在此處得到結果,但要確保你能處理整個表達式,因為后面這是一個很有用的技能。