Learn Python The Hard Way学习(28)
上一节中的逻辑组合被称为:布尔逻辑表达式。布尔逻辑被用在程序的许多地方,它们是计算机运算的基础,了解他们就像学习音乐要了解音阶一样。看下面的题目,然后写出答案,最后在python解析器中验证答案。
[*]TrueandTrue
[*]FalseandTrue
[*]1==1and2==1
[*]"test"=="test"
[*]1==1or2!=1
[*]Trueand1==1
[*]Falseand0!=0
[*]Trueor1==1
[*]"test"=="testing"
[*]1!=0and2==1
[*]"test"!="testing"
[*]"test"==1
[*]not(TrueandFalse)
[*]not(1==1and0!=1)
[*]not(10==1or1000==1000)
[*]not(1!=10or3==4)
[*]not("testing"=="testing"and"Zed"=="CoolGuy")
[*]1==1andnot("testing"==1or1==0)
[*]"chunky"=="bacon"andnot(3==4or3==3)
[*]3==3andnot("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)
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中很多类似!=和==这些操作符,试着找出一些等价操作符,比如<或者<=。
OperationMeaningNotes<strictly less than<=less than or equal>strictly greater than>=greater than or equal==equal!=not equal(1)isobject identityisnotnegated object identity
2. 写出等价操作符的名称。
上面表格有了。
3. 在python中测试新的布尔操作符。
4. 把第三节的那张纸丢掉,我们不再需要它了。
页:
[1]