【学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编程的核心,熟练掌握它们对于编写高效、清晰的代码至关重要。