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


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

看下面的题目,然后写出答案,最后在python解析器中验证答案。
True and True
False and True
1 == 1 and 2 == 1
"test" == "test"
1 == 1 or 2 != 1
True and 1 == 1
False and 0 != 0
True or 1 == 1
"test" == "testing"
1 != 0 and 2 == 1
"test" != "testing"
"test" == 1
not (True and False)
not (1 == 1 and 0 != 1)
not (10 == 1 or 1000 == 1000)
not (1 != 10 or 3 == 4)
not ("testing" == "testing" and "Zed" == "Cool Guy")
1 == 1 and not ("testing" == 1 or 1 == 0)
"chunky" == "bacon" and not (3 == 4 or 3 == 3)
3 == 3 and not ("testing" == "testing" or "Python" == "Fun")
下面我会给出一些理清复杂逻辑的方法。

当你看到逻辑判断语句的时候,你可以通过下面的过程解决:
找到==或者!=,判断他们的真假。
判断括号里面的真假。
找到not,判断真假。
最后找到and或者or,判断真假。
这些做完,就可以解决问题了。
我们来看上面的第20题:
3 != 4 and not ("testing" != "test" or "Python" == "Python")
我们现在安装上面的步骤,然后写出每步的结果:
先找==和!=符号,判断后变成:True and not (True or True)
判断括号中的真假:True and not True
判断not:True and False
最后就是: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. 把第三节的那张纸丢掉,我们不再需要它了。

作者:lixiang0522
 

相关内容

    暂无相关文章

评论关闭