《笨办法学Python》20-----逻辑关系与布尔表达式
计算机的逻辑就是在程序的某个位置检查一个布尔表达式的结果是真(True)是假(False)。
在前面的章节中已经提到过python中的逻辑运算符,见运算符
python中有以下3种逻辑运算符
and 与
or 或
not 非
逻辑运算符在运算优先级中,排名最后。运算符优先级参考运算符优先级
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")
在书写布尔表达式时最好使用括号进行优先级限定,有利于看代码阅读。
关于真值判断需要注意的一点在python文档中已经提到:
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
•None
•False
•zero of any numeric type, for example, 0, 0L, 0.0, 0j.
•any empty sequence, for example, '', (), [].
•any empty mapping, for example, {}.
•instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. [1]
All other values are considered true — so objects of many types are always true.
Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)
python中值被认为假的并不是只有False,还有数字0,None类型,空字符串,空列表,空字典,空元组等。