第三篇:函数、文件与异常处理 / Functions, Files & Exception Handling

3.1 定义与调用函数 / Defining and Calling Functions

中文 :用 def 定义函数。参数可以有默认值,调用时可使用关键字参数。return 返回结果,无返回值时返回 None。

English : Define functions with def. Parameters can have defaults; keyword arguments are supported at call time. return sends back a result; without it, the function returns None.

python

复制代码
def greet(name, greeting="Hello"):
    """返回问候语 / Return a greeting message."""
    return f"{greeting}, {name}!"

print(greet("Alice"))                    # Hello, Alice!
print(greet("Bob", greeting="你好"))      # 你好, Bob!
print(greet(name="Carol", greeting="Hi")) # Hi, Carol!

3.2 参数类型 / Parameter Kinds

中文 :*args 收集位置参数为元组,**kwargs 收集关键字参数为字典。二者可组合使用。

English : *args collects positional arguments into a tuple; **kwargs collects keyword arguments into a dict. They can be combined.

python

复制代码
def summarize(*args, **kwargs):
    print("位置参数 / positional:", args)
    print("关键字参数 / keyword:", kwargs)

summarize(1, 2, 3, name="Alice", age=20)
# 位置参数 / positional: (1, 2, 3)
# 关键字参数 / keyword: {'name': 'Alice', 'age': 20}


def apply(func, *args):
    """把函数应用到参数上 / apply a function to arguments."""
    return func(*args)

print(apply(max, 3, 7, 2))   # 7

3.3 读写文件 / Reading and Writing Files

中文 :用 with open(...) as f 打开文件,代码块结束时自动关闭。encoding="utf-8" 处理中文必须显式指定。

English : Use with open(...) as f to open files; they close automatically when the block ends. Always specify encoding="utf-8" for Chinese text.

python

复制代码
# 写入文件 / write to file
with open("demo.txt", "w", encoding="utf-8") as f:
    f.write("第一行 / line one\n")
    f.write("第二行 / line two\n")

# 读取整个文件 / read entire file
with open("demo.txt", "r", encoding="utf-8") as f:
    content = f.read()
print(content)

# 逐行读取 / read line by line
with open("demo.txt", "r", encoding="utf-8") as f:
    for line_num, line in enumerate(f, start=1):
        print(f"{line_num}: {line.strip()}")

3.4 异常处理 / Exception Handling

中文 :try 块放可能出错的代码,except 捕获指定异常,else 在无异常时执行,finally 无论是否出错都执行。

English : Put risky code in try, catch specific exceptions with except, run else if no exception occurred, and finally always runs.

python

复制代码
def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("错误 / Error: 除数不能为零 / division by zero")
        return None
    except TypeError as e:
        print(f"类型错误 / Type error: {e}")
        return None
    else:
        print("计算成功 / Calculation succeeded")
        return result
    finally:
        print("执行完毕 / Done\n")

print(safe_divide(10, 2))   # 5.0
print(safe_divide(10, 0))   # None
print(safe_divide("a", 2))  # None

3.5 自定义异常 / Custom Exceptions

中文 :继承 Exception 定义业务异常,便于上层代码精确捕获。

English : Subclass Exception to define business-specific errors that callers can catch precisely.

python

复制代码
class InsufficientBalanceError(Exception):
    """余额不足异常 / Raised when balance is insufficient."""
    pass


def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientBalanceError(
            f"余额 {balance} 不足以取出 {amount} / "
            f"balance {balance} is insufficient for {amount}"
        )
    return balance - amount


try:
    withdraw(100, 150)
except InsufficientBalanceError as e:
    print("捕获异常 / Caught:", e)

3.6 综合练习 / Comprehensive Exercise

中文 :读取一个文本文件,统计行数和字符数,若文件不存在则给出提示。

English: Read a text file, count lines and characters, and print a message if the file doesn't exist.

python

复制代码
def analyze_file(path):
    """统计文件行数与字符数 / Count lines and characters."""
    try:
        with open(path, "r", encoding="utf-8") as f:
            lines = f.readlines()
    except FileNotFoundError:
        print(f"文件不存在 / File not found: {path}")
        return
    except UnicodeDecodeError:
        print(f"编码错误 / Encoding error: {path}")
        return

    line_count = len(lines)
    char_count = sum(len(line) for line in lines)
    print(f"行数 / Lines: {line_count}")
    print(f"字符数 / Characters: {char_count}")


analyze_file("demo.txt")
analyze_file("missing.txt")

https://github.com/0voice

相关推荐
2601_9679801136 分钟前
python+appium自动化测试如何控制App的启动和退出
android·自动化测试·python·appium·设备调试
lcj25111 小时前
[C++] C++11
开发语言·c++·笔记
威哥爱编程2 小时前
模拟面试智能体开发实战 12:每篇都能跑不等于接起来能跑,端到端联调收官把十一块拼图合成一个能用的智能体
python·agent·harmonyos
威哥爱编程2 小时前
模拟面试智能体开发实战 11:报告只躺在后端怎么复盘,把总评搬上手机还要适配大小屏
python·agent·harmonyos
2601_967987373 小时前
Python 实现行为驱动开发 (BDD) 自动化测试详解
自动化测试·python·bdd·behave·gherkin
Evand J3 小时前
【MATLAB例程】基于IMM-CKF的AOA+测距融合的二维移动目标跟踪定位
开发语言·matlab·目标跟踪
数字融合3 小时前
透明化视频驱动化工生产动态三维重建管控技术
大数据·人工智能·python
JianZhen✓4 小时前
IM 聊天列表为什么总“消息乱跳“:有序插入、时间轴派生、本地截断、已读回执
开发语言·前端·php
FungLeo4 小时前
FengCMS · PHP+MySQL 升级实录· 代码审计怎么闭环:REVIEW到 CLOSURE 四件套,12 个域90 篇修复文档跟到底
开发语言·mysql·php·代码审计·fengcms
屿华AI4 小时前
AUTOSAR 实战-诊断工具 | DTC/Event/FiM 故障报告自动化:DEM 诊断数据采集与解析
python·测试工具·自动化·汽车