目的:熟練與掌握邏輯表達式
在Python交互頁面輸入以下邏輯語句,確認寫的答案是否正確:
True and True # True
False and False # False
1 == 1 and 2 == 1 # False
"test" == "test" # True
1 == 1 or 2 != 1 # True
True or 1 == 1 # True
"test" == "testing" # False
1 != 0 and 2 == 1 # False
"test" != "testing" # True
"test" == 1 # False
not (True and False) # True
not (1 == 1 and 0 != 1) # False
not (10 == 1 or 1000 == 1000 ) # False
not (1 != 10 or 3 == 4) # False
not ("testing" == "testing" and "Shui" == "mahua") # True
1 == 1 and not ("testing" == 1 or 1 == 0) # True
"chunky" == "bacon" and not (3 == 4 or 3 == 3) # False
3 == 3 and not ("testing" == "testing" or "Python" == "Fun") # False
常見問題問答:
1)爲什麼 "test" and "test" 返回 "test", 1 and 1 返回 1,而不是返回 True 呢?
Python 和很多語言一樣,都是返回兩個被操作對象中的一個,而非它們的布爾表達式True 或 False 。這意味着如果你寫了 False and 1 ,你得到的是第一個操作字元(False),而非第二個字元(1)。多多實驗一下。
2)!= 和 <> 有何不同?
Python 中 <> 將被逐漸棄用, != 纔是主流,除此以爲沒什麼不同。
3)有沒有短路邏輯?
有的。任何以 False 開頭的 and 語句都會直接被處理成 False 並且不會繼續檢查後面語句了。任何包含 True 的 or 語句,只要處理到 True 這個字樣,就不會繼續向下推算,而是直接返回 True 了。