《笨方法学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")

输出

 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 >>> 

加分习题

Python 里还有很多和 != 、 == 类似的操作符. 试着尽可能多地列出 Python 中的等价运算符。例如 < 或者 <= 就是。

写出每一个等价运算符的名称。例如 != 叫 “not equal(不等于)”。

== (equal) 等于

>= (greater-than-equal) 大于等于

<= (less-than-equal) 小于等于

在 python 中测试新的布尔操作。在敲回车前你需要喊出它的结果。不要思考,凭自己的第一感就可以了。把表达式和结果用笔写下来再敲回车,最后看自己做对多少,做错多少。

把习题 3 那张纸丢掉,以后你不再需要查询它了。

常见问题回答

为什么 "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 了。不过还是要确保整个语句都能正常处理,以方便日后理解和使用代码。

原文地址:https://www.cnblogs.com/python2webdata/p/10186764.html