笨方法学Python 习题 28: 布尔表达式练习

来源:互联网 发布:淘宝店铺装修设计说明 编辑:程序博客网 时间:2024/05/21 14:46

#!usr/bin/python# -*-coding:utf-8-*-True and Trueprint ("True")False and Trueprint ("False")1 == 1 and 2 == 1print ("False")"test" == "test"print ("True")1 == 1 or 2 != 1print ("True")True and 1 == 1print ("True")False and 0 != 0print ("False")True or 1 == 1print ("True")"test" == "testing"print ("False")1 != 0 and 2 == 1print ("False")"test" != "testing"print ("True")"test" == 1print ("False")not (True and False)print ("True")not (1 == 1 and 0 != 1)print ("False")not (10 == 1 or 1000 == 1000)print ("False")not (1 != 10 or 3 == 4)print ("False")not ("testing" == "testing" and "Zed" == "Cool Guy")print ("True")1 == 1 and not ("testing" == 1 or 1 == 0)print ("True")"chunky" == "bacon" and not (3 == 4 or 3 == 3)print ("False")3 == 3 and not ("testing" == "testing" or "Python" == "Fun")print ("False")
运行结果如下:

>>> True and TrueTrue>>> False and TrueFalse>>> 1 == 1 and 2 == 1False>>> "test" == "test"True>>> 1 == 1 or 2 != 1True>>> True and 1 == 1True>>> False and 0 != 0False>>> True or 1 == 1True>>> "test" == "testing"False>>> 1 != 0 and 2 == 1False>>> "test" != "testing"True>>> "test" == 1False>>> 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 "Zed" == "Cool Guy")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>>> 

加分习题

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