控制流与函数进阶

Python 控制流与函数进阶:从循环到模式匹配

在掌握 Python 基础语法后,理解控制结构(如 ifforwhile)、函数定义(包括匿名函数)以及 Python 3.10+ 新特性(如结构化模式匹配)是进阶的关键一步。本文通过一系列实用示例,带你系统梳理这些核心概念。


1. 条件分支:if-elif-elsematch-case

传统多分支判断(if-elif-else

age = int(input('Please input your age: '))

if age <= 10:
    print('You are a child')
elif age <= 18:
    print('You are a teenager')
elif age <= 65:
    print('You are an adult (eligible to vote)')
else:
    print('You are a senior citizen')

print('Program ends.')

✅ 适用于大多数条件判断场景,逻辑清晰,兼容所有 Python 版本。


结构化模式匹配(match-case,Python 3.10+)

Python 3.10 引入了类似其他语言 switch模式匹配 语法:

age = 9

match age:
    case e if e < 10:
        print('You are a child')
    case _:
        print('You are a teenager or older')
  • case _ 是通配符(相当于 default);
  • 支持守卫条件(if 子句),实现更灵活的匹配。

⚠️ 注意:match-case 不是简单的值比较,而是模式匹配,未来可扩展至复杂数据结构(如字典、类实例)。


2. 循环结构:forwhile

for 循环:遍历序列(半开区间)

# 遍历 range(左闭右开)
for n in range(0, 10):
    print(f'第{n}次打印')

# 遍历字符串
for c in 'hello world':
    print(c)
  • range(0, 10) 生成 0 到 9(不包含 10);
  • for 可直接遍历任何可迭代对象(字符串、列表、元组等)。

while 循环:条件驱动

n = 0
while n < 10:
    print(n)
    n += 1
print('Done')
  • 适用于不确定循环次数的场景;
  • 务必确保循环变量会变化,避免死循环。

3. 匿名函数:lambda

lambda 用于创建小型匿名函数,常用于高阶函数(如 sortmapfilter):

# 创建一个“加法器”闭包
def make_incrementor(n):
    return lambda x, *args: x + n

f = make_incrementor(42)
print(f(2))  # 44
print(f(3))  # 45

在排序中的应用

pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')]

# 按字符串(第二项)降序排序
pairs.sort(key=lambda x: x[1], reverse=True)
print(pairs)

# 再按升序排回来
pairs.sort(key=lambda x: x[1])
print(pairs)

lambda x: x[1] 表示“以元组的第二个元素作为排序键”。

🔁 注意:list.sort() 是原地排序,而 sorted() 返回新列表。


4. 模块化编程:自定义模块与导入

定义函数(my_tes.py

# my_tes.py
def http_error(status):
    match status:
        case 400 | 399:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"
  • 使用 match-case 处理多种 HTTP 状态码;
  • 支持“或”匹配(400 | 399)。

导入并使用模块(module_test.py

# module_test.py
from chap3.test import test11          # 假设 test11 是另一个模块函数
from chap4.my_tes import http_error    # 导入上面定义的函数

print(http_error(401))  # Something's wrong with the internet
print(test11())         # 调用其他模块功能

📦 最佳实践

  • 将功能拆分为多个 .py 文件(模块);
  • 使用 from ... import ... 按需导入,避免命名冲突。

5. 补充:三目运算符(条件表达式)

Python 中的“三目运算”写法:

x = 10
res = '>10' if x > 10 else '<10'
print(res)  # '<10'

语法:value_if_true if condition else value_if_false


总结对比表

特性 语法 适用场景
多条件分支 if-elif-else 通用,兼容性好
模式匹配 match-case Python 3.10+,状态码/类型分发
循环 for item in iterable 遍历已知序列
循环 while condition 条件控制循环
匿名函数 lambda args: expr 简短函数,配合高阶函数使用
模块导入 from module import func 代码组织与复用

学习建议

  • 动手实验:修改示例中的数值、条件、数据结构,观察输出变化;
  • 组合使用:例如在 for 循环中使用 lambda 排序,或在 match 中调用模块函数;
  • 版本注意match-case 需 Python ≥ 3.10,部署前确认环境。

🐍 小贴士:Python 的设计哲学是“可读性至上”。即使有新特性(如 :=match),也要优先选择团队最熟悉、最易维护的写法。


希望这篇整理能帮助你巩固 Python 控制流与函数的核心知识!欢迎将你的实践心得留言分享~


posted @ 2026-01-03 21:40  言下忘言  阅读(4)  评论(0)    收藏  举报