当前位置: 首页 > news >正文

语言基础篇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 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打断")
http://www.lryc.cn/news/152690.html

相关文章:

  • MATLAB算法实战应用案例精讲-【概念篇】构建数据指标方法(补充篇)
  • 【pyqt5界面化工具开发-12】QtDesigner图形化界面设计
  • CXL.mem S2M Message 释义
  • 设计模式—外观模式(Facade)
  • Stack Overflow开发者调查发布:AI将如何协助DevOps
  • 去掉鼠标系列之二:Sublime Text快捷键使用指南
  • docker-compose安装node-exporter, prometheus, grafana
  • 企业架构LNMP学习笔记10
  • [国产MCU]-W801开发实例-I2C控制器
  • 植物根系基因组与数据分析
  • 2.3 数据模型
  • RT-Thread 中断管理学习(一)
  • 学习周报9.3
  • win10 查看指定进程名的端口号
  • 函数的递归调用
  • 李宏毅机器学习笔记:RNN循环神经网络
  • 基于JavaWeb和mysql实现校园订餐前后台管理系统(源码+数据库)
  • CNN 01(CNN简介)
  • AI大模型的使用-让AI帮你写单元测试
  • vscode调教配置:快捷修复和格式化代码
  • pear admin 后端启动
  • C++:输出系统时间(及报错处理)
  • 使用Windbg动态调试排查软件启动不了的问题
  • Swift 技术 视频播放器滚动条(源码)
  • PixelSNAIL论文代码学习(2)——门控残差网络的实现
  • WebGPU学习(9)---使用Pipeline Overridable Constants
  • javaweb入门版学生信息管理系统-增删改查+JSP+Jstl+El
  • 云原生Kubernetes:K8S概述
  • nmap的使用
  • Python爬虫-某网酒店数据