一个 case 也可以设置多个匹配条件,条件使用 | 隔开,例如:
...
case 401|403|404:
return "Not allowed"
Python 中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else。
示例: Python中if语句的一般形式如下所示:
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
在嵌套 if 语句中,可以把 if...elif...else 结构放在另外一个 if...elif...else 结构中。
if 表达式1:
语句
if 表达式2:
语句
elif 表达式3:
语句
else:
语句
elif 表达式4:
语句
else:
语句
Python 3.10 增加了 match...case 的条件判断,不需要再使用一连串的 if-else 来判断了。
语法格式如下:
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 都无法匹配时,匹配这条,保证永远会匹配成功。
以上是一个输出 HTTP 状态码的实例,输出结果为:
Bad request
一个 case 也可以设置多个匹配条件,条件使用 | 隔开,例如:
...
case 401|403|404:
return "Not allowed"
Python 中的循环语句有 for 和 while。
Python 中 while 语句的一般形式:
while 判断条件(condition): 执行语句(statements)……
示例
#!/usr/bin/env python3
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 到 %d 之和为: %d" % (n,sum))