1.什么是条件控制语句
Python 条件控制语句是通过一条或多条语句的执行结果来判断需要执行那一分支的代码。常用的条件控制语句有if
语句和match...case
语句。
2. if 语句
if
语句通常有三种格式:
(1)if 形式
if 表达式:
代码块
例1:
if a > 0:
print("正数")
(2)if else 形式
if 表达式:
代码块 1
else:
代码块 2
例2:
if a > 0:
print("正数")
else:
print("负数")
(3)if elif else 语句形式
if 表达式 1:
代码块 1
elif 表达式 2:
代码块 2
elif 表达式 3:
代码块 3
...//其它elif语句
else:
代码块 n
例3:
if a < 60:
print("不及格")
elif 60 <= a < 70:
print("良好")
elif 70 <= a < 80:
print("中上")
elif 80 <= a < 90:
print("优秀")
else:
print("完美")
3. if 语句注意事项
- if 语句中的"条件表达式"可以是一个单一的值或者变量,也可以是由运算符组成的复杂语句,形式不限,只要它能得到一个值就行。
- "条件表达式"以及最后的
else
后面必须的加上:
结尾。 - 使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
- 如果"条件表达式"为
空字符串、空列表 、空元组、空字典、None
时,会把它们的结果当做“假”来处理。
4. if 嵌套
if 嵌套是指在一个if语句的执行代码中添加另一个if语句,常见的格式如下:
if 表达式1:
语句
if 表达式2:
语句
elif 表达式3:
语句
else:
语句
elif 表达式4:
语句
else:
语句
例4:
score = int(input("请输入你的成绩:"))
if score >= 60:
if score >= 80:
print("真棒,你的成绩很优秀!")
else:
print("你的成绩属于良好,要继续努力哦!")
else:
print("你的成绩未及格,要拼命努力哦!")
5. match…case 语句
与java的switch case语句类似,主要是用match
后的对象会依次与 case
后的内容进行匹配,如果匹配成功,则执行匹配到的表达式,否则直接跳过,_
可以匹配一切,即都不匹配时默认执行该分支代码。
match subject:
case pattern_1:
action_1
case pattern_2:
action_2
case pattern_3:
action_3
case _:
action_wildcard
例5:
match code:
case 200:
print("success")
case 400:
print("faild")
case 404:
print("Not found")
case _:
print("others")
## 一个 case 也可以设置多个匹配条件,条件使用 | 隔开,例如:
case 400 | 404:
print("error")