分支结构
概述
程序的默认执行顺序是顺序结构——从上到下逐条执行。但很多场景下需要根据不同条件选择不同的执行路径,这就是分支结构(也叫选择结构)。
典型的例子:游戏过关时根据分数决定进入下一关还是 Game Over。
if / elif / else 分支结构
Python 用 if、elif、else 三个关键字构造分支结构。
基本 if 结构
height = float(input('身高(cm): '))
weight = float(input('体重(kg): '))
bmi = weight / (height / 100) ** 2
print(f'{bmi = :.1f}')
if 18.5 <= bmi < 24:
print('你的身材很棒!')
注意:
if条件后要有英文冒号:,代码块用缩进(通常4个空格)表示,不要用 Tab。
if-else 结构
height = float(input('身高(cm): '))
weight = float(input('体重(kg): '))
bmi = weight / (height / 100) ** 2
print(f'{bmi = :.1f}')
if 18.5 <= bmi < 24:
print('你的身材很棒!')
else:
print('你的身材不够标准!')
多分支结构
height = float(input('身高(cm): '))
weight = float(input('体重(kg): '))
bmi = weight / (height / 100) ** 2
print(f'{bmi = :.1f}')
if bmi < 18.5:
print('体重过轻')
elif bmi < 24:
print('身材很棒')
elif bmi < 27:
print('体重过重')
elif bmi < 30:
print('轻度肥胖')
elif bmi < 35:
print('中度肥胖')
else:
print('重度肥胖')
说明:Python 支持连续比较
18.5 <= bmi < 24,C/Java 等语言需要写成bmi >= 18.5 and bmi < 24。
match-case 结构(Python 3.10+)
Python 3.10 引入了类似 switch 的 match-case 语法:
status_code = int(input('响应状态码: '))
match status_code:
case 400: description = 'Bad Request'
case 401: description = 'Unauthorized'
case 403: description = 'Forbidden'
case 404: description = 'Not Found'
case 418: description = 'I am a teapot'
case 429: description = 'Too Many Requests'
case _: description = 'Unknown Status' # 通配符
print('状态码描述:', description)
模式合并
使用 | 合并多个匹配值:
match status_code:
case 400 | 405: description = 'Invalid Request'
case 401 | 403 | 404: description = 'Not Allowed'
case _: description = 'Unknown'
应用实例
实例1:分段函数求值
$$
y = \begin{cases} 3x - 5 & (x > 1) \ x + 2 & (-1 \le x \le 1) \ 5x + 3 & (x < -1) \end{cases}
$$
x = float(input('x = '))
if x > 1:
y = 3 * x - 5
elif x >= -1:
y = x + 2
else:
y = 5 * x + 3
print(f'{y = }')
提示:分支可以嵌套,但应遵循"扁平化优于嵌套"原则。
实例2:百分制成绩转等级
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 = 'E'
print(f'{grade = }')
实例3:计算三角形周长和面积
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
if a + b > c and a + c > b and b + c > a:
perimeter = a + b + c
s = perimeter / 2
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5 # 海伦公式
print(f'周长: {perimeter}')
print(f'面积: {area}')
else:
print('不能构成三角形')
总结
- 分支结构使程序具备"选择性执行"的能力
if-elif-else是最常用的多分支结构- Python 用缩进表示代码块,保持缩进一致非常重要
match-case(Python 3.10+)是多分支的简洁替代方案