一个 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))
如果 while 后面的条件语句为 false 时,则执行 else 的语句块。
语法格式如下:
while <expr>: <statement(s)> else: <additional_statement(s)>
示例:
#!/usr/bin/python3
count = 0
while count < 5:
print (count, " 小于 5")
count = count + 1
else:
print (count, " 大于或等于 5")
Python for 循环可以遍历任何可迭代对象,如一个列表或者一个字符串。
for循环的一般格式如下:
for <variable> in <sequence>:
<statements>
else:
<statements>
示例:
#!/usr/bin/python3
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
print(site)
在 Python 中,for...else 语句用于在循环结束后执行一段代码。
关于else 是否有用的思考:python中for - else中的else存在的必要性
语法格式如下:
for item in iterable:
# 循环主体
else:
# 循环结束后执行的代码
当循环执行完毕(即遍历完 iterable 中的所有元素)后,会执行 else 子句中的代码,如果在循环过程中遇到了 break 语句,则会中断循环,此时不会执行 else 子句。
break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。
continue 语句被用来告诉 Python 跳过当前循环块中的剩余语句,然后继续进行下一轮循环。
Python pass是空语句,是为了保持程序结构的完整性。