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

【学Python自动化】 4. Python 控制流与函数学习笔记

一、if 语句

基本语法


x = int(input("请输入一个整数: "))if x < 0:x = 0print('负数变为零')
elif x == 0:print('零')
elif x == 1:print('一')
else:print('更多')

特点

  • elif 是 else if 的缩写

  • 可以有0个或多个 elif 部分

  • else 部分是可选的

  • 替代其他语言的 switch/case 语句

二、for 语句

遍历序列


words = ['cat', 'window', 'defenestrate']
for w in words:print(w, len(w))

输出:


cat 3
window 6
defenestrate 12

安全修改字典的两种策略


users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}# 策略1:迭代副本
for user, status in users.copy().items():if status == 'inactive':del users[user]# 策略2:创建新字典
active_users = {}
for user, status in users.items():if status == 'active':active_users[user] = status

三、range() 函数

基本用法


for i in range(5):print(i)  # 输出: 0,1,2,3,4list(range(5, 10))     # [5, 6, 7, 8, 9]
list(range(0, 10, 3))  # [0, 3, 6, 9]
list(range(-10, -100, -30))  # [-10, -40, -70]

按索引迭代序列


a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):print(i, a[i])

range对象特性

  • 不真正存储所有值,节省内存

  • 只有在被迭代时才生成值

  • 是可迭代对象(iterable)

四、break 和 continue

break 示例


for n in range(2, 10):for x in range(2, n):if n % x == 0:print(f"{n} = {x} * {n//x}")break

continue 示例


for num in range(2, 10):if num % 2 == 0:print(f"偶数: {num}")continueprint(f"奇数: {num}")

五、循环的 else 子句

质数检测示例


for n in range(2, 10):for x in range(2, n):if n % x == 0:print(n, '=', x, '*', n//x)breakelse:# 循环正常结束(未break)时执行print(n, '是质数')

六、pass 语句

占位符用法


# 无限循环等待中断
while True:pass  # 按 Ctrl+C 中断# 空类定义
class MyEmptyClass:pass# 待实现的函数
def initlog(*args):pass  # 记得实现这个!

七、match 语句(Python 3.10+)

基本模式匹配


def http_error(status):match status:case 400:return "错误请求"case 404:return "未找到"case 418:return "我是茶壶"case _:return "网络有问题"

元组解包模式


def handle_point(point):match point:case (0, 0):print("原点")case (0, y):print(f"Y={y}")case (x, 0):print(f"X={x}")case (x, y):print(f"X={x}, Y={y}")case _:raise ValueError("不是点")

类模式匹配


class Point:__match_args__ = ('x', 'y')def __init__(self, x, y):self.x = xself.y = ydef where_is(point):match point:case Point(0, 0):print("原点")case Point(0, y):print(f"Y={y}")case Point(x, 0):print(f"X={x}")case Point():print("其他位置")

八、定义函数

斐波那契函数


def fib(n):"""打印小于n的斐波那契数列"""a, b = 0, 1while a < n:print(a, end=' ')a, b = b, a + bprint()fib(2000)  # 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

返回列表的函数


def fib2(n):"""返回小于n的斐波那契数列列表"""result = []a, b = 0, 1while a < n:result.append(a)a, b = b, a + breturn resultf100 = fib2(100)  # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

九、函数参数详解

1 默认参数值

def ask_ok(prompt, retries=4, reminder='请重试!'):while True:reply = input(prompt)if reply in {'y', 'ye', 'yes'}:return Trueif reply in {'n', 'no', 'nop', 'nope'}:return Falseretries -= 1if retries < 0:raise ValueError('无效的用户响应')print(reminder)
2 关键字参数

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):print("-- This parrot wouldn't", action, end=' ')print("if you put", voltage, "volts through it.")print("-- Lovely plumage, the", type)print("-- It's", state, "!")# 有效调用
parrot(1000)
parrot(voltage=1000)
parrot(voltage=1000000, action='VOOOOOM')
parrot(action='VOOOOOM', voltage=1000000)
3 特殊参数

def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):print(pos1, pos2, pos_or_kwd, kwd1, kwd2)# 正确调用
f(1, 2, 3, kwd1=4, kwd2=5)
f(1, 2, pos_or_kwd=3, kwd1=4, kwd2=5)
4 任意参数列表

def write_multiple_items(file, separator, *args):file.write(separator.join(args))def concat(*args, sep="/"):return sep.join(args)concat("earth", "mars", "venus")  # "earth/mars/venus"
concat("earth", "mars", "venus", sep=".")  # "earth.mars.venus"
5 解包参数

# 列表解包
args = [3, 6]
list(range(*args))  # [3, 4, 5]# 字典解包
def parrot(voltage, state='a stiff', action='voom'):print(f"-- This parrot wouldn't {action}", end=' ')print(f"if you put {voltage} volts through it.", end=' ')print(f"E's {state}!")d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
parrot(**d)
6 Lambda 表达式

# 匿名函数
f = lambda x: x + 42
f(1)  # 43# 返回lambda函数
def make_incrementor(n):return lambda x: x + nf = make_incrementor(42)
f(0)  # 42
f(1)  # 43# 作为参数传递
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
# [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

十、编码风格建议(PEP 8)

主要规范

  • 缩进: 4个空格,不要用制表符

  • 行宽: 不超过79个字符

  • 空行: 分隔函数和类,以及代码块

  • 注释: 单独一行,说明代码功能

  • 命名:

    • 类名: UpperCamelCase

    • 函数名: lowercase_with_underscores

    • 方法第一个参数: self

  • 运算符: 前后加空格

  • 编码: 使用UTF-8

示例


def calculate_average(numbers):"""计算数字列表的平均值"""total = sum(numbers)count = len(numbers)return total / count if count > 0 else 0

这些控制流和函数特性是Python编程的核心,熟练掌握它们对于编写高效、清晰的代码至关重要。

http://www.dtcms.com/a/358205.html

相关文章:

  • FlowUs AI-FlowUs息流推出的AI创作助手
  • DAY 18 推断聚类后簇的类型 - 2025.8.30
  • ADB常用命令大全
  • Linux驱动开发重要操作汇总
  • 1.8 Memory
  • vue表格底部添加合计栏,且能跟主表同时滑动
  • 【Linux基础】深入理解计算机启动原理:MBR主引导记录详解
  • U-Boot移植过程中的关键目录文件解析
  • 循迹小车控制实验:实验介绍
  • 基于FPGA的简易医疗呼叫器实现,包含testbench
  • Linux 830 shell:expect,ss -ant ,while IFS=read -r line,
  • 在 VS2017 中使用 Visual Leak Detector 检测内存泄漏(记录一下 以前开发中使用过)
  • 数据结构(C语言篇):(七)双向链表
  • 学习游戏制作记录(视觉上的优化)
  • GRPO(组相对策略优化):大模型强化学习的高效进化
  • MySQL独占间隙锁为什么会互相兼容?
  • 基于Ultralytics YOLO通用目标检测训练体系与PyTorch EfficientNet的图像分类体系实现
  • 用Git在 Ubuntu 22.04(Git 2.34.1)把 ROS 2 工作空间上传到全新的 GitHub 仓库 步骤
  • MCU启动过程简介
  • 为多种业态注入智能化发展新活力的智慧地产开源了
  • Java 常见异常系列:ClassNotFoundException 类找不到
  • Qt线程提升:深度指南与最佳实践
  • 操作系统上的Docker安装指南:解锁容器化新世界
  • 《潮汐调和分析原理和应用》之四S_Tide使用1
  • 一个wordpress的网站需要什么样的服务器配置
  • 数据结构(力扣刷题)
  • 【gflags】安装与使用
  • LangChain实战(五):Document Loaders - 从多源加载数据
  • ARM 裸机开发 知识点
  • 【70页PPT】WMS助力企业数字化转型(附下载方式)