一、前言
程序不是一条直线,而是一张决策网。
当用户登录时,系统要判断账号密码是否正确;
当处理订单时,程序要根据金额决定是否打折;
当解析数据时,代码要区分空值、数字还是字符串......
这些"根据不同情况做不同事"的逻辑,在编程中称为 分支结构(Branching Structure)。
在 Python 中,分支结构的核心就是 if 语句家族。
本文将带你: ✅ 掌握 if/elif/else 基础语法
✅ 理解多条件组合(and/or/not)
✅ 避开嵌套过深的"金字塔陷阱"
✅ 使用三元表达式简化简单判断
✅ 写出高效、可读的分支逻辑
二、分支结构基础:if、elif、else
1. 单分支:if
python
age = 18
if age >= 18:
print("你已成年")
# 输出:你已成年
✅ 特点:条件为真(Truthy)时执行,否则跳过。
2. 双分支:if-else
python
score = 85
if score >= 60:
print("及格")
else:
print("不及格")
# 输出:及格
💡 适用于"非此即彼"的场景。
3. 多分支:if-elif-else
python
grade = 85
if grade >= 90:
print("优秀")
elif grade >= 80:
print("良好")
elif grade >= 60:
print("及格")
else:
print("不及格")
# 输出:良好
⚠️ 关键规则:
- 从上到下依次判断
- 一旦某个条件为真,执行对应代码块后立即退出整个
if结构- 后续
elif/else不再检查
三、条件表达式的组合:and、or、not
Python 支持用逻辑运算符组合多个条件:
| 运算符 | 含义 | 示例 |
|---|---|---|
and |
与(都为真才真) | x > 0 and x < 10 |
or |
或(一个为真即真) | x < 0 or x > 100 |
not |
非(取反) | not is_empty |
示例:用户登录验证
python
username = "admin"
password = "123456"
if username == "admin" and password == "123456":
print("登录成功")
else:
print("用户名或密码错误")
💡 短路求值(Short-circuit Evaluation) :
a and b:若a为假,则不计算b
a or b:若a为真,则不计算b可用于安全访问属性:
pythonif user and user.is_active: # 防止 user 为 None 时报错 ...
四、常见陷阱与避坑指南
❌ 陷阱 1:误用 = 而非 ==
python
# 错误!这是赋值,不是比较
if x = 5:
...
# 正确
if x == 5:
...
✅ Python 3 中
if x = 5:会直接报语法错误,但初学者仍需警惕。
❌ 陷阱 2:忽略条件顺序(尤其 elif)
python
score = 95
if score >= 60:
print("及格") # 先匹配,后续不再判断!
elif score >= 90:
print("优秀") # 永远不会执行!
✅ 修复 :条件应从最严格到最宽松排列:
python
if score >= 90:
print("优秀")
elif score >= 60:
print("及格")
❌ 陷阱 3:过度嵌套,形成"金字塔"
python
if user:
if user.is_active:
if user.balance > 0:
if not user.is_banned:
process_order(user)
✅ 优化方案:提前返回(Guard Clauses)
python
if not user:
return
if not user.is_active:
return
if user.balance <= 0:
return
if user.is_banned:
return
process_order(user)
🌟 优点:逻辑扁平,易读易维护。
❌ 陷阱 4:对非布尔值做"显式比较"
python
# 不推荐
if len(items) == 0:
print("列表为空")
# 推荐(利用真值测试)
if not items:
print("列表为空")
✅ Pythonic 原则:利用对象自身的布尔值,而非与 True/False/0/"" 显式比较
五、高级技巧:三元表达式与条件表达式
对于简单 if-else,可用 三元表达式 一行搞定:
python
# 传统写法
if age >= 18:
status = "成人"
else:
status = "未成年"
# 三元表达式(推荐)
status = "成人" if age >= 18 else "未成年"
语法:
python
value_if_true if condition else value_if_false
应用场景:
- 变量赋值
- 返回值选择
- 列表推导式中的条件
python
# 列表推导式示例
numbers = [1, 2, 3, 4, 5]
squared = [x**2 if x % 2 == 0 else x for x in numbers]
# 结果:[1, 4, 3, 16, 5]
⚠️ 注意:不要嵌套三元表达式!可读性极差:
python# ❌ 难以理解 result = a if cond1 else (b if cond2 else c)
六、最佳实践:写出清晰的分支逻辑
✅ 1. 条件尽量简单,复杂逻辑提取为函数
python
# 差
if user.age >= 18 and user.country in ["CN", "US"] and not user.is_banned:
# 好
def is_eligible(user):
return (
user.age >= 18
and user.country in ["CN", "US"]
and not user.is_banned
)
if is_eligible(user):
...
✅ 2. 使用 in 判断成员关系
python
# 推荐
if status in ("active", "pending"):
...
# 避免
if status == "active" or status == "pending":
...
✅ 3. 避免重复判断
python
# 低效
if x > 0:
print("正数")
if x < 0:
print("负数")
if x == 0:
print("零")
# 高效(互斥条件用 elif)
if x > 0:
print("正数")
elif x < 0:
print("负数")
else:
print("零")
七、总结:分支结构使用 checklist
| 场景 | 推荐写法 |
|---|---|
| 简单真假判断 | if condition: |
| 二选一 | if-else 或三元表达式 |
| 多级分类 | if-elif-else(条件从严到宽) |
| 安全访问属性 | if obj and obj.attr: |
| 复杂条件 | 提取为函数 + 描述性命名 |
| 空值/空容器判断 | if not items: 而非 len(items)==0 |
🌈 记住 :
好的分支逻辑,
不是"能跑就行",
而是"一眼看懂"。
八、结语
感谢您的阅读!如果你有任何疑问或想要分享的经验,请在评论区留言交流!