现在的位置: 首页 > 综合 > 正文

Learn Python The Hard Way学习(28) – 布尔运算练习

2013年10月08日 ⁄ 综合 ⁄ 共 1435字 ⁄ 字号 评论关闭

上一节中的逻辑组合被称为:布尔逻辑表达式。布尔逻辑被用在程序的许多地方,它们是计算机运算的基础,了解他们就像学习音乐要了解音阶一样。

看下面的题目,然后写出答案,最后在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. 找到==或者!=,判断他们的真假。
  2. 判断括号里面的真假。
  3. 找到not,判断真假。
  4. 最后找到and或者or,判断真假。
  5. 这些做完,就可以解决问题了。
我们来看上面的第20题:
3 != 4 and not ("testing" != "test" or "Python" == "Python")
我们现在安装上面的步骤,然后写出每步的结果:
  1. 先找==和!=符号,判断后变成:True and not (True or True)
  2. 判断括号中的真假:True and not True
  3. 判断not:True and False
  4. 最后就是:False
警告:刚开始你会觉得这个表达式很复杂,不要灰心,这些练习只是有一些初步了解,只要我们不放过一些错误的地方,慢慢我们会熟悉这些运算的。

运行结果

root@he-desktop:~# python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> True and True
True
>>> False and True
False
>>> 1 == 1 and 2 == 1
False
>>> "test" == "test"
True

加分练习
1. python中很多类似!=和==这些操作符,试着找出一些等价操作符,比如<或者<=。
Operation Meaning Notes
< strictly less than  
<= less than or equal  
> strictly greater than  
>= greater than or equal  
== equal  
!= not equal (1)
is object identity  
is not negated object identity  

2. 写出等价操作符的名称。
上面表格有了。
3. 在python中测试新的布尔操作符。
4. 把第三节的那张纸丢掉,我们不再需要它了。

抱歉!评论已关闭.