语言基础篇9——Python流程控制

流程控制

顺序结构、条件结构、循环结构,顺序结构由自上而下的语句构成,条件结构由ifmatch-case构成,循环结构由forwhile构成。

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 dataclass


class Point1:
    __match_args__ = ('x', 'y')

    def __init__(self, x, y):
        self.x = x
        self.y = y


@dataclass
class Point2:
    x: int
    y: int


def 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 -= 1
    print(count)
    # break
    # continue
else:
    print("循环正常执行完毕,没有被break打断")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值