文章目录
目录
- 一、基础逻辑运算符
- 二、真值表与运算规则
- 1. and 运算符
- 2. or 运算符
- 3. not 运算符
- 三、短路求值特性
- 1. and 的短路行为
- 2. or 的短路行为
- 3. 实际应用:避免除零错误
- 四、运算符优先级
- 五、非布尔类型的处理
- 六、实际应用案例
- 1. 设置默认值
- 2. 条件验证链
- 3. 链式比较
- 七、常见错误与注意事项
- 1. 混淆逻辑与按位运算符
- 2. 忽略运算符优先级
- 总结
Python 包含三个核心逻辑运算符:
| 运算符 | 描述 | 示例 | 结果 |
|---|---|---|---|
and |
逻辑与 | True and True |
True |
or |
逻辑或 | False or True |
True |
not |
逻辑非 | not False |
True |
| 左操作数 | 右操作数 | 结果 |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
| 左操作数 | 右操作数 | 结果 |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
| 操作数 | 结果 |
|---|---|
| True | False |
| False | True |
def check():
print("执行检查")
return True
print(False and check()) # 输出 False,不执行check()
def load_data():
print("加载数据")
return []
print(True or load_data()) # 输出 True,不执行load_data()
x = 0
if x != 0 and (10 / x > 2): # 安全判断
print("条件成立")
else:
print("跳过危险计算")
优先级顺序(从高到低)

示例解析
result = not False or True and False # 等效于 (not False) or (True and False) → True or False → True
Python 将以下值视为 False:
NoneFalse0(各种数值类型的零)- 空序列/集合:
"",[],{},set() - 其他值视为
True
返回值规则: 通常备用来赋值,省略 if 判断
| 运算符 | 返回规则 |
|---|---|
| and | 返回第一个假值或最后一个真值 |
| or | 返回第一个真值或最后一个假值 |
| not | 始终返回布尔值 |
示例
# and
## 如果 a 为真,b 为真,输出 b
c = 1 and 2
print('c =', c) # c = 2
## 如果 a 为假,b 为假,输出 a
c = [] and 0
print('c =', c) # c = []
## 如果 a 为假,b 为真,输出 a
c = [] and 1
print('c =', c) # c = []
## 如果 a 为 真,b 为假,输出 b
c = 1 and 0
print('c =', c) # c = 0
# 总结:a 为假,输出a;a为真,输出b
# or
# 如果 a 为真,b 为真,输出 a
c = 1 or 2
print('c =', c) # c = 1
# 如果 a 为假,b 为假,输出 b
c = [] or 0
print('c =', c) # c = 0
# 如果 a 为假,b 为真,输出 b
c = [] or 1
print('c =', c) # c = 1
# 如果 a 为 真,b 为假,输出 a
c = 1 or 0
print('c =', c) # c = 1
# 总结:a 为假,输出b;a为真,输出a
结合短路逻辑理解即可
username = input("用户名: ") or "Guest"
print(f"欢迎, {username}")
def validate(email, password):
return "@" in email and len(password) >= 8
x = 5
print(0 < x < 10) # 等效于 (0 < x) and (x < 10)
# 错误用法(应使用 and/or)
if (a > 5) & (b < 10): # 正确应使用 and
pass
# 错误写法
if not x > 5 or y < 3: # 实际是 (not x) > 5 or y < 3
# 正确写法
if not (x > 5) or y < 3: # 或 x <= 5 or y < 3
- 副作用操作
# 危险写法(依赖短路特性修改状态)
def update():
global counter
counter += 1
return True
flag = False and update() # update() 不会执行
- 使用 and/or 时注意短路特性优化性能
- 复杂表达式使用括号明确优先级
- 理解非布尔值的真假判断逻辑
- 避免在逻辑表达式中引入副作用
通过掌握这些要点,可以编写更高效、安全的 Python 条件判断逻辑。
到此这篇关于Python逻辑运算符详解与实际应用指南的文章就介绍到这了,更多相关Python逻辑运算符内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!
您可能感兴趣的文章:
- 总结Python中逻辑运算符的使用
- python中and和or逻辑运算符的用法示例
- 详解Python中的元组与逻辑运算符
- Python入门_浅谈逻辑判断与运算符
- Python运算符教程之逻辑门详解
- Python3逻辑运算符与成员运算符