《笨方法學Python》加分題28

 1 #!usr/bin/python
 2 # -*-coding:utf-8-*-
 3  
 4 True and True
 5 print ("True")
 6 False and True
 7 print ("False")
 8 1 == 1 and 2 == 1
 9 print ("False")
10 "test" == "test"
11 print ("True")
12 1 == 1 or 2 != 1
13 print ("True")
14 True and 1 == 1
15 print ("True")
16 False and 0 != 0
17 print ("False")
18 True or 1 == 1
19 print ("True")
20 "test" == "testing"
21 print ("False")
22 1 != 0 and 2 == 1
23 print ("False")
24 "test" != "testing"
25 print ("True")
26 "test" == 1
27 print ("False")
28 not (True and False)
29 print ("True")
30 not (1 == 1 and 0 != 1)
31 print ("False")
32 not (10 == 1 or 1000 == 1000)
33 print ("False")
34 not (1 != 10 or 3 == 4)
35 print ("False")
36 not ("testing" == "testing" and "Zed" == "Cool Guy")
37 print ("True")
38 1 == 1 and not ("testing" == 1 or 1 == 0)
39 print ("True")
40 "chunky" == "bacon" and not (3 == 4 or 3 == 3)
41 print ("False")
42 3 == 3 and not ("testing" == "testing" or "Python" == "Fun")
43 print ("False")

 

輸出python

 1 >>> True and True
 2 True
 3 >>> False and True
 4 False
 5 >>> 1 == 1 and 2 == 1
 6 False
 7 >>> "test" == "test"
 8 True
 9 >>> 1 == 1 or 2 != 1
10 True
11 >>> True and 1 == 1
12 True
13 >>> False and 0 != 0
14 False
15 >>> True or 1 == 1
16 True
17 >>> "test" == "testing"
18 False
19 >>> 1 != 0 and 2 == 1
20 False
21 >>> "test" != "testing"
22 True
23 >>> "test" == 1
24 False
25 >>> not (True and False)
26 True
27 >>> not (1 == 1 and 0 != 1)
28 False
29 >>> not (10 == 1 or 1000 == 1000)
30 False
31 >>> not (1 != 10 or 3 == 4)
32 False
33 >>> not ("testing" == "testing" and "Zed" == "Cool Guy")
34 True
35 >>> 1 == 1 and not ("testing" == 1 or 1 == 0)
36 True
37 >>> "chunky" == "bacon" and not (3 == 4 or 3 == 3)
38 False
39 >>> 3 == 3 and not ("testing" == "testing" or "Python" == "Fun")
40 False
41 >>> 

加分習題less

Python 裏還有不少和 != 、 == 相似的操做符. 試着儘量多地列出 Python 中的等價運算符。例如 < 或者 <= 就是。測試

寫出每個等價運算符的名稱。例如 != 叫 「not equal(不等於)」。spa

== (equal) 等於code

>= (greater-than-equal) 大於等於對象

<= (less-than-equal) 小於等於blog

在 python 中測試新的布爾操做。在敲回車前你須要喊出它的結果。不要思考,憑本身的第一感就能夠了。把表達式和結果用筆寫下來再敲回車,最後看本身作對多少,作錯多少。utf-8

把習題 3 那張紙丟掉,之後你再也不須要查詢它了。class

 

常見問題回答test

爲何 "test" and "test" 返回 "test", 1 and 1 返回 1,而不是返回 True 呢?

Python 和不少語言同樣,都是返回兩個被操做對象中的一個,而非它們的布爾表達式 True 或 False 。這意味着若是你寫了 False and 1 ,你獲得的是第一個操做字元(False),而非第二個字元(1)。多多實驗一下。

!= 和 <> 有何不一樣?

Python 中 <> 將被逐漸棄用, != 纔是主流,除此覺得沒什麼不一樣。

有沒有短路邏輯?

有的。任何以 False 開頭的 and 語句都會直接被處理成 False 而且不會繼續檢查後面語句了。任何包含 True 的 or 語句,只要處理到 True 這個字樣,就不會繼續向下推算,而是直接返回 True 了。不過仍是要確保整個語句都能正常處理,以方便往後理解和使用代碼。

相關文章
相關標籤/搜索