50 选择结构

常见的选择结构有单分支选择结构、双分支选择结构、多分支选择结构及嵌套的分支结构,也可以构造跳转表来实现类似的逻辑。循环结构和异常处理结构中也可以实现带有 else 子句,可以看作特殊形式的选择结构。

所有的 Python 合法表达式都可以作为条件表达式,包括含有函数调用的表达式。在 Python 的语法中,条件表达式不允许使用赋值运算符 "=",避免了误将关系运算符 "==" 写成赋值运算符 "=" 带来的麻烦。在条件表达式中使用赋值运算符 "=" 将抛出异常,提示语法错误。

1 单分支选择结构

cpp 复制代码
x = input('x, y:')
a, b = map(int, x.split())
if a > b:
    a, b = b, a
print(a, b)
cpp 复制代码
if 3 > 2: print('True')
if True: print('hello');print('world')

2 双分支选择结构

cpp 复制代码
# 通过鸡兔同笼问题演示双分支结构的用法
m, n = map(int, input('m, n: ').split())
y = (n - 2 * m) / 2
if int(y) == y:
    print('x, y:', int(m - y), int(y))
else:
    print('No solution due to data error')

Python 提供了一个三元运算符,并且在三元运算符构成的表达式中还可以嵌套三元运算符,可以实现与选择结构相似的效果。语法为
value1 if condition else value2

cpp 复制代码
a = 5
print(6) if a > 3 else print(5)
print(6 if a > 3 else 5)  # 结果与上一行代码一样,但代码含义不同

b = 6 if a > 13 else 9  # 赋值运算符的优先级非常低
print(b)

import math

# 还没有导入 random 模块
x = math.sqrt(9) if 5 > 3 else random.randint(1, 100)
print(x)

虽然三元运算符可以嵌套使用,可以实现复杂的多分支选择结构的效果,但这样的代码可读性非常差,不建议使用。

cpp 复制代码
def func(x):
    return x * x


x = 3
print((1 if x > 2 else 0) if func(x) > 5 else ('a' if x < 5 else 'b'))
x = 0
print((1 if x > 2 else 0) if func(x) > 5 else ('a' if x < 5 else 'b'))

3 多分支选择结构

cpp 复制代码
def func(score):
    if score > 100 or score < 0:
        return 'wrong score'
    elif score >= 90:
        return 'A'
    elif score >= 80:
        return 'B'
    elif score >= 70:
        return 'C'
    elif score >= 60:
        return 'D'
    else:
        return 'E'


score = [68, 98, 45, 22, 70, 72, 84]
print(score)
print([func(i) for i in score])

4 选择结构的嵌套

cpp 复制代码
def func(score):
    star = 'DCBAA*'
    if score > 100 or score < 0:
        return 'wrong score'
    else:
        index = (score - 60) // 10
        if index >= 0:
            return star[index]
        else:
            return star[-1]


score = [68, 98, 45, 22, 70, 72, 84]
print(score)
print([func(i) for i in score])
相关推荐
troy12814 分钟前
分布式系统框架选型指南:主流框架优缺点深度对比
python·django·pygame
PC2005-cloud19 分钟前
DSH 白嫖指南:接入 Command Code Go、WorkBuddy 与 Trae 的免费额度
开发语言·后端·golang
129Lab26 分钟前
BMS算法快速原型开发:AI辅助实现扩展卡尔曼滤波(EKF)SOC估算从理论到代码落地
python·嵌入式开发·bms·卡尔曼滤波·电池管理系统·soc估算
萧鼎29 分钟前
safetensors 库的安装、核心语法与实战用法,安全保存模型权重
python·开源·教程·python库·safetensors
千里码aicood38 分钟前
基于Python语言的测量程序设计
开发语言·python
charlie11451419142 分钟前
C++ 的新标准容器:flat_map、inplace_vector 与 mdspan
开发语言·c++·开源项目
2601_962300811 小时前
用PyTorch Lightning简化空间分析:Python和机器学习的力量
python·深度学习·机器学习·空间分析·pytorchlightning
唠玖馆1 小时前
c++AVL树
开发语言·c++
2401_858286111 小时前
130.【C语言】可变参数宏
c语言·开发语言
霸道流氓气质1 小时前
通义千问 VL & Audio:图像、视频、语音多模态 Java 集成深度解析
java·开发语言·音视频