
上QQ阅读APP看书,第一时间看更新
2.4.3 逻辑运算符和逻辑表达式
对于较为复杂的条件,必须使用逻辑运算符和逻辑表达式。
1.逻辑运算符
Python提供的逻辑运算符,见表2-6。假设表中变量a为10,变量b为20。
表2-6 逻辑运算符

2.逻辑表达式
逻辑表达式是指用逻辑运算符连接若干关系表达式或逻辑值而成的表达式。逻辑表达式的值也是一个布尔值(True或False),当把True和False作为值书写时,首字母要大写。逻辑表达式一般格式为:

注意:
1)逻辑运算符的优先级低于关系运算符和算术运算符。
2)在没有圆括号的情况下,三个逻辑运算符的优先级为:not>and>or。
【例2-11】 判断闰年的条件是:能被4整除但不能被100整除,或者能被400整除的年份是闰年。
解答:根据以上判断闰年的条件,写出判断闰年的逻辑表达式,年用变量year。
