Python3 条件控制
约 449 字大约 2 分钟
2024-08-10
Python 条件语句是通过一条或多条语句的执行结果(True 或者 False)来决定执行的代码块
if 语句
Python 中 if 语句的一般形式如下
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3如果
condition_1为True将执行statement_block_1块语句如果
condition_1为False,将判断condition_2如果
condition_2为True将执行statement_block_2块语句如果
condition_2为False,将执行statement_block_3块语句
Python 中用 elif 代替了 else if,所以 if 语句的关键字为:if – elif – else
注意:
1、每个条件后面要使用冒号
:,表示接下来是满足条件后要执行的语句块2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块
3、在
Python中没有switch...case语句,但在Python3.10版本添加了match...case,功能也类似
if 嵌套
在嵌套 if 语句中,可以把 if – elif – else 结构放在另外一个 if – elif – else 结构中
if 表达式1:
语句
if 表达式2:
语句
elif 表达式3:
语句
else:
语句
elif 表达式4:
语句
else:
语句match...case
Python 3.10 增加了 match...case 的条件判断,不需要再使用一连串的 if-else 来判断了
match 后的对象会依次与 case 后的内容进行匹配,如果匹配成功,则执行匹配到的表达式,否则直接跳过,_ 可以匹配一切
match subject:
case <pattern_1>:
<action_1>
case <pattern_2>:
<action_2>
case <pattern_3>:
<action_3>
case _:
<action_wildcard>case _: 类似于 C 和 Java 中的 default:,当其他 case 都无法匹配时,匹配这条,保证永远会匹配成功
mystatus=400
print(http_error(400))
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"