网站首页 > 知识剖析 正文
一、单分支选择结构
if 表达式:
语句块
二、双分支结构:
if 表达式:
语句块1
else:
语句块2
三、多分支选择结构
if 表达式1:
语句块1
elif 表达式2:
语句块2
elif 表达式3:
语句块3
else:
语句块4
其中,关键字elif是else if的缩写。
if score > 100 or score < 0:
return 'wrong score.must between 0 and 100.'
elif score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
四、选择结构的嵌套
if 表达式1:
语句块1
if 表达式2:
语句块2
else:
语句块3
else:
if 表达式4:
语句块4
degree = 'DCBAAE'
if score > 100 or score < 0:
return 'wrong score.must between 0 and 100.'
else:
index = (score - 60) // 10
if index >= 0:
return degree[index]
else:
return degree[-1]
五、三元运算符
- Python提供了一个三元运算符,并且在三元运算符构成的表达式中还可以嵌套三元运算符,可以实现与选择结构相似的效果。语法为
>>>value1 if condition else value2
- 当条件表达式condition的值与True等价时,表达式的值为value1,否则表达式的值为value2。
>>> b = 6 if 5>13 else 9 #赋值运算符优先级非常低
>>> b
猜你喜欢
- 2024-11-13 pandas如何操作Excel?还不会的,看此一篇足矣
- 2024-11-13 一日一技:Python中的string.rindex()方法
- 2024-11-13 买不到口罩怎么办?Python 爬虫帮你时刻盯着自动下单!| 原力计划
- 2024-11-13 [oeasy]python0078_设置索引颜色_index_color_ansi_控制终端颜色
- 2024-11-13 Python基础教程:新手朋友在python中常见的错误信息汇总
- 2024-11-13 python index ValueError: substring not found
- 2024-11-13 将多行多列的数据拆分成多行一列的数据(index函数)
- 2024-11-13 Python数据分析实战-Series转DataFrame并将index设为新的一列
- 2024-11-13 盘点Python 初学者最容易犯的10大错误!你中招了吗?
- 2024-11-13 1-6,0基础学Python创建list,Python中布尔类型按照索引访问list
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)