昨天你学到的逻辑组合的正式名称是“布尔逻辑表达式 (boolean logic expression)”。在编程中,布 尔逻辑可以说是无处不在。它们是计算机运算的基础和重要组成部分,掌握它们就跟学音乐掌握音阶一样重 要。
在这节练习中,你将在 python 里使用到上节学到的逻辑表达式。先为下面的每一个逻辑问题写出你认 为的答案,每一题的答案要么为 True 要么为 False。写完以后,你需要将 python 运行起来,把这些逻辑 语句输入进去,确认你写的答案是否正确。
1. True and True True
2. False and True True
3. 1==1and2==1 False
4. "test" == "test" True
5. 1==1or2!=1 True
6. True and1==1 True
7. False and 0 != 0 False
8. True or 1==1 True
9. "test" == "testing" False
10. 1!=0 and 2==1 False
11. "test" != "testing" True
12. "test" == 1 False
13. not (True and False) True
14. not(1==1and 0!=1) False
15. not (10 == 1 or 1000 == 1000) Flse
16. not(1!=10 or 3==4) False
17. not ("testing" == "testing" and "Zed" == "Cool Guy") True
18. 1==1 and not("testing"==1 or 1==0) True
19. "chunky" == "bacon" and not (3 == 4 or 3 == 3) False
20. 3 == 3 and not ("testing" == "testing" or "Python" == "Fun") False
所有的布尔逻辑表达式都可以用下面的简单流程得到结果:
1. 找到相等判断的部分 (== or !=),将其改写为其最终值 (True 或 False)。 2. 找到括号里的 and/or,先算出它们的值。
3. 找到每一个 not,算出他们反过来的值。
4. 找到剩下的 and/or,解出它们的值。
5. 等你都做完后,剩下的结果应该就是 True 或者 False 了。