1. 程式人生 > >笨辦法學Python(二十八)

笨辦法學Python(二十八)

等你 utils 很難 cti style app 運算 技術分享 util

習題 28: 布爾表達式練習

上一節你學到的邏輯組合的正式名稱是“布爾邏輯表達式(boolean logic expression)”。在編程中,布爾邏輯可以說是無處不在。它們是計算機運算的基礎和重要組成部分,掌握它們就跟學音樂掌握音階一樣重要。

在這節練習中,你將在 python 裏使用到上節學到的邏輯表達式。先為下面的每一個邏輯問題寫出你認為的答案,每一題的答案要麽為 True 要麽為 False。寫完以後,你需要將python 運行起來,把這些邏輯語句輸入進去,確認你寫的答案是否正確。

  1. True and True
  2. False and True
  3. 1 == 1 and 2 == 1
  4. "test" == "test"
  5. 1 == 1 or 2 != 1
  6. True and 1 == 1
  7. False and 0 != 0
  8. True or 1 == 1
  9. "test" == "testing"
  10. 1 != 0 and 2 == 1
  11. "test" != "testing"
  12. "test" == 1
  13. not (True and False)
  14. not (1 == 1 and 0 != 1)
  15. not (10 == 1 or 1000 == 1000)
  16. not (1 != 10 or 3 == 4)
  17. not ("testing" == "testing" and "Zed" == "Cool Guy")
  18. 1 == 1 and not ("testing" == 1 or 1 == 0)
  19. "chunky" == "bacon" and not (3 == 4 or 3 == 3)
  20. 3 == 3 and not ("testing" == "testing" or "Python" == "Fun")

在本節結尾的地方我會給你一個理清復雜邏輯的技巧。

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

  1. 找到相等判斷的部分 (== or !=),將其改寫為其最終值 (True 或 False)。
  2. 找到括號裏的 and/or,先算出它們的值。
  3. 找到每一個 not,算出他們反過來的值。
  4. 找到剩下的 and/or,解出它們的值。
  5. 等你都做完後,剩下的結果應該就是 True 或者 False 了。

下面我們以 #20 邏輯表達式演示一下:

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

接下來你將看到這個復雜表達式是如何逐級解為一個單獨結果的:

  1. 解出每一個等值判斷:
    1. 3 != 4True: True and not ("testing" != "test" or "Python" == "Python")
    2. "testing" != "test"True: True and not (True or "Python" == "Python")
    3. "Python" == "Python": True and not (True or True)
  2. 找到括號中的每一個 and/or :
    1. (True or True) 為 True: True and not (True)
  3. 找到每一個 not 並將其逆轉:
    1. not (True) 為 False: True and False
  4. 找到剩下的 and/or,解出它們的值:
    1. 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(二十八)