习题26、恭喜你,现在可以考试了!
习题27、记住逻辑关系
逻辑术语
- and 与
- or 或
- not 非
- != (not equal) 不等于
- == (equal) 等于
- >= (greater-than-equal) 大于等于
- <= (less-than-equal) 小于等于
- True 真
- False 假
小结
- 直接学习布尔算法,不用背这些东西,可不可以?
当然可以,不过这么一来,当你写代码的时候,你就需要回头想布尔函数的原理,这样你写代码的速度就慢了。而如果你记下来了的话,不但锻炼了自己的记忆力,而且让这些应用变成了条件反射,而且理解起来就更容易了。当然,你觉得哪个方法好,就用哪个方法好了。
习题28、布尔表达式练习
练习截屏
技巧
所有的布尔逻辑表达式都可以用下面的简单流程得到结果:
- 找到相等判断的部分 (== or !=),将其改写为其最终值 (True 或 False)。
- 找到括号里的 and/or,先算出它们的值。
- 找到每一个 not,算出他们反过来的值。
- 找到剩下的 and/or,解出它们的值。
- 等你都做完后,剩下的结果应该就是 True 或者 False 了。
小结
- 为什么
"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
了。不过还是要确保整个语句都能正常处理,以方便日后理解和使用代码。
习题29、如果(if)
#!/usr/bin/python
# -*- coding:utf-8 -*-
people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The world is dry!"
dogs += 5
if people >= dogs:
print "People are greater than or equal to dogs."
if people <= dogs:
print "People are less than or equal to dogs."
if people == dogs:
print "People are dogs."
小结
+=
是什么意思?
x += 1
和x = x + 1
一样,只不过可以少打几个字母。你可以把它叫做加值符。一样的,你后面还会学到-=
以及很多别的表达式。
习题30、Else 和 If
#!/usr/bin/python
# -*- coding:utf-8 -*-
people = 30
cars = 40
buses = 15
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."
if buses > cars:
print "That's too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We still can't decide."
if people > buses:
print "Alright, let's just take the buses."
else:
print "Fine, let's stay home then."
小结
- 如果多个
elif
区块都是True
是 python 会如何处理?
Python 只会运行它碰到的是True
的第一个区块,所以只有第一个为True
的区块会被
运行。