7. 逻辑运算符与条件表达式
三大逻辑运算符
| 运算符 | 含义 | 示例 | 结果 |
|---|---|---|---|
and | 与(两者都为 True 才 True) | True and False | False |
or | 或(只要有一个 True 就 True) | True or False | True |
not | 非(取反) | not True | False |
运算符优先级
逻辑运算符的优先级从高到低为:not > and > or。
⚠️ 优先级陷阱
year % 4 == 0 and year % 100 != 0 or year % 400 == 0 等价于 (year % 4 == 0 and year % 100 != 0) or year % 400 == 0,因为 and 优先级高于 or。
建议在复杂表达式中加括号明确优先级,避免歧义。
比较运算符
| 运算符 | 含义 | 示例 |
|---|---|---|
== | 等于 | a == b |
!= | 不等于 | a != b |
> / < | 大于 / 小于 | a > b |
>= / <= | 大于等于 / 小于等于 | a >= b |
a <= x < b | 链式比较(Python 特色) | 18.5 <= bmi < 24 |
经典应用:判定闰年
闰年规则:能被 4 整除但不能被 100 整除,或者能被 400 整除。
python
year = int(input("请输入年份:"))
# not > and > or,所以不需要加括号
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print("闰年")
else:
print("平年")
📝 样例输入:
输入
2024
▶ 运行结果:
输出
请输入年份:2024
闰年
推荐加括号的写法,更清晰:
python
year = int(input("请输入年份:"))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("闰年")
else:
print("平年")
📝 样例输入:
输入
2024
▶ 运行结果:
输出
请输入年份:2024
闰年