一、条件分支基础
1. if语句
语法定义:
if 条件表达式:
代码块
功能:当条件表达式为True时执行代码块
参数:
条件表达式:返回布尔值的任何有效Python表达式
返回值:无
应用案例:
# 用户年龄验证
age = int(input("请输入您的年龄: "))
if age >= 18:
print("您已成年,可以访问此内容")
# 密码强度检查(PEP8风格)
password = input("设置密码: ")
if len(password) < 8:
print("密码强度不足:至少需要8个字符")
注意事项:
冒号(:)不能省略
代码块必须缩进(通常4个空格)
避免将条件表达式写在同一行
if语句流程图:
2. if-else语句
语法定义:
if 条件表达式:
代码块1
else:
代码块2
功能:二选一执行路径
应用案例:
# 用户登录验证
username = input("用户名: ")
password = input("密码: ")
if username == "admin"and password == "123456":
print("登录成功")
else:
print("用户名或密码错误")
# 数字奇偶判断(实用案例)
number = int(input("请输入整数: "))
if number % 2 == 0:
print(f"{number}是偶数")
else:
print(f"{number}是奇数")
if-else语句流程图:
表1 if vs if-else对比
二、多条件分支
1. if-elif-else语句
语法定义:
if 条件1:
代码块1
elif 条件2:
代码块2
...
else:
代码块N
功能:多条件分支选择
应用案例:
# 成绩等级评定(实用案例)
score = float(input("请输入成绩: "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"成绩等级: {grade}")
# BMI分类(实际应用)
height = float(input("身高(m): "))
weight = float(input("体重(kg): "))
bmi = weight / (height ** 2)
if bmi < 18.5:
category = "偏瘦"
elif18.5 <= bmi < 24:
category = "正常"
elif24 <= bmi < 28:
category = "超重"
else:
category = "肥胖"
print(f"BMI: {bmi:.1f},分类: {category}")
图:if-elif-else流程图:
2. 嵌套if语句
语法定义:
if 条件1:
if 条件2:
代码块
应用案例:
# 闰年判断(实用算法)
year = int(input("请输入年份: "))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f"{year}年是闰年")
else:
print(f"{year}年不是闰年")
else:
print(f"{year}年是闰年")
else:
print(f"{year}年不是闰年")
# 用户权限检查(实际应用)
has_account = True
is_premium = False
balance = 150
if has_account:
if is_premium:
print("尊享会员服务")
else:
if balance >= 100:
print("普通用户服务")
else:
print("余额不足")
else:
print("请先注册账号")
注意事项:
嵌套层级不宜超过3层
复杂嵌套应考虑拆分为函数
使用布尔变量简化条件
三、三元表达式
语法定义:
值1 if 条件 else 值2
功能:简化条件赋值
应用案例:
# 简单条件赋值
age = 20
status = "成年"if age >= 18else"未成年"
print(status)
# 实际应用:求绝对值
num = -5
abs_num = num if num >= 0else -num
print(f"绝对值: {abs_num}")
# 列表推导式中的条件
numbers = [1, -2, 3, -4, 5]
positive = [x if x > 0else0for x in numbers]
print(f"非负数列表: {positive}")
三元表达式流程图:
表2 三元表达式适用场景
四、match-case语句(Python 3.10+)
语法定义:
match 值:
case 模式1:
代码块1
case 模式2:
代码块2
case _:
默认代码块
功能:结构化模式匹配
应用案例:
# HTTP状态码处理
status_code = int(input("请输入状态码: "))
match status_code:
case200:
print("请求成功")
case404:
print("页面未找到")
case500 | 502 | 503:
print("服务器错误")
case _:
print(f"未知状态码: {status_code}")
# 数据结构匹配(实用案例)
defprocess_data(data):
match data:
case {"type": "user", "name": name, "age": age}:
print(f"用户: {name}, 年龄: {age}")
case {"type": "order", "id": id, "items": items}:
print(f"订单#{id} 包含{len(items)}件商品")
case [x, y, z]:
print(f"三维坐标: ({x}, {y}, {z})")
case _:
print("未知数据类型")
process_data({"type": "user", "name": "Alice", "age": 25})
match-case语句流程图:
五、应用实践
1. 分支优化技巧
实用技巧:
# 1. 使用字典代替复杂分支
defhandle_status(code):
return {
200: lambda: print("成功"),
404: lambda: print("未找到"),
500: lambda: print("服务器错误")
}.get(code, lambda: print(f"未知状态码: {code}"))()
# 2. 提前返回减少嵌套
defcalculate_discount(user_type, price):
ifnot user_type == "VIP":
return price # 提前返回
if price > 1000:
return price * 0.8
return price * 0.9
# 3. 使用布尔变量简化条件
is_valid = (age >= 18) and (has_id)
if is_valid:
print("验证通过")
表3 分支优化方法对比
2. 常见错误避免
错误案例与修正:
# 错误1:误用赋值运算符
if status = "active": # 报错
pass
# 修正:
if status == "active":
pass
# 错误2:遗漏冒号
if age >= 18# 报错
print("成年")
# 修正:
if age >= 18:
print("成年")
# 错误3:不必要的嵌套
if x > 0:
if y > 0:
print("第一象限")
# 修正:
if x > 0and y > 0:
print("第一象限")
分支语句错误检查流程图
六、实际应用案例
1. 权限检查
def check_permission(user, resource):
"""实用权限检查函数"""
ifnot user["is_active"]:
returnFalse
if user["is_admin"]:
returnTrue
match resource["type"]:
case"public":
returnTrue
case"private":
return user["id"] == resource["owner_id"]
case"premium":
return user["is_premium"]
case _:
returnFalse
# 使用示例
user = {
"id": 101,
"is_active": True,
"is_admin": False,
"is_premium": True
}
resource = {
"type": "premium",
"owner_id": 100
}
if check_permission(user, resource):
print("访问 granted")
else:
print("访问 denied")
2. 折扣计算
def calculate_discount(user_type, cart_value):
"""实用折扣计算函数"""
# 基础折扣
if user_type == "VIP":
discount = 0.2if cart_value > 1000else0.1
elif user_type == "MEMBER":
discount = 0.1if cart_value > 500else0.05
else:
discount = 0
# 节日促销
if is_holiday_season():
discount = min(discount + 0.1, 0.3)
# 最终价格
final_price = cart_value * (1 - discount)
returnround(final_price, 2)
# 使用示例
price = calculate_discount("VIP", 1200)
print(f"最终价格: ¥{price:.2f}")
总结
核心知识点:
基础分支:if/elif/else实现条件控制
三元表达式:简化条件赋值
match-case:结构化模式匹配(Python 3.10+)
最佳实践:避免嵌套、使用字典映射等
建议:
保持分支结构扁平化
复杂逻辑拆分为函数
优先使用match-case处理多分支
始终遵循PEP8代码风格
分支语句选择指南
简单判断 if
二选一 if-else
多条件 if-elif-else
值匹配 match-case
更新日期:2025-05-08
交流讨论:欢迎在评论区留言!
重要提示:本文主要是记录自己的学习与实践过程,所提内容或者观点仅代表个人意见,只是我以为的,不代表完全正确,不喜请勿关注。
领取专属 10元无门槛券
私享最新 技术干货