语言基础篇9——Python流程控制
流程控制
顺序结构、条件结构、循环结构,顺序结构由自上而下的语句构成,条件结构由if
、match-case
构成,循环结构由for
、while
构成。
if语句
flag = 1
if flag == 1:print("A")
elif flag == 2:print("B")
else:print("C")
match-case语句
结构模式匹配,Python3.10引入
PEP 634 – Structural Pattern Matching: Specification
PEP 635 – Structural Pattern Matching: Motivation and Rationale
PEP 636 – Structural Pattern Matching: Tutorial
# literal pattern
def structural_pattern_matching(value):match value:case 1:print("A")case "2":print("B")case True:print("C")case False:print("D")case None:print("E")structural_pattern_matching(1)
structural_pattern_matching("2")
structural_pattern_matching(None)
structural_pattern_matching("ABC")
# capture pattern
# guard是case的一部分,为if语句def structural_pattern_matching(value):match value:case {'sub': sub, **rest}:print(f'{sub=} {rest=}')case {'route': route}:print(f'ROUTE: {route}')structural_pattern_matching({'route': '/auth/login'})
structural_pattern_matching({'route': '/auth/login', 'sub': {'a': 1}})def go(obj):match obj:case 'go', [direction, num] if isinstance(num, int):print(f"go {direction} {num}")case 'stop', *other:print('stop', *other)go(['go', ['east', 3]])
go(['go', ['east', "3"]])
go(['stop', '3', '2', '1'])
# as pattern
def structural_pattern_matching(value):match value:case ["go", ("north" | "south" | "east" | "west") as direction]:print(f'go {direction}')case _:print("B")structural_pattern_matching(['go', 'west'])
# or pattern
def structural_pattern_matching(value):match value:case 0 | 1 | 2:print('A')case True | False:print('B')structural_pattern_matching(1)
# wildcard pattern
# 通配符,匹配任意值,通配符匹配必须要在最后
# SyntaxError: wildcard makes remaining patterns unreachable
def structural_pattern_matching(value):match value:case 1:print("A")case _:print("B")structural_pattern_matching(1)
structural_pattern_matching("2")
# Matching builtin classes
# 可以按类型匹配
def structural_pattern_matching(obj):match obj:case str() as s:print(s)case [0, tuple() as t]:print(f'{t}')case list() as l:print(l)structural_pattern_matching("ooo") # ooo
structural_pattern_matching([0, (1,)]) # (1,)
structural_pattern_matching([(1,)]) # [(1,)]
structural_pattern_matching([1, 2, 3]) # [1, 2, 3]
# Matching positional attributes
from dataclasses import dataclassclass Point1:__match_args__ = ('x', 'y')def __init__(self, x, y):self.x = xself.y = y@dataclass
class Point2:x: inty: intdef structural_pattern_matching(value):match value:case Point1(x, y):print(f'{x=}, {y=}')case Point2(x, y):print(f'{x=}, {y=}')structural_pattern_matching(Point1(1, 2))
structural_pattern_matching(Point2(3, 4))
for语句
for i in range(10):print(i)
else:print("break跳出不执行else")
while语句
count = 10
while count:count -= 1print(count)# break# continue
else:print("循环正常执行完毕,没有被break打断")