news 2026/10/30 9:58:41

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

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
第三篇:函数、文件与异常处理 / Functions, Files Exception Handling

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

中文:用def定义函数。参数可以有默认值,调用时可使用关键字参数。return返回结果,无返回值时返回None。
English: Define functions withdef. Parameters can have defaults; keyword arguments are supported at call time.returnsends back a result; without it, the function returnsNone.

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:*argscollects positional arguments into a tuple;**kwargscollects 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: Usewith open(...) as fto open files; they close automatically when the block ends. Always specifyencoding="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 intry, catch specific exceptions withexcept, runelseif no exception occurred, andfinallyalways 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: SubclassExceptionto 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")

github.0voice

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/10/30 9:47:25

数据中心液冷技术:解决高密度散热难题的工程实践

1. 数据中心热密度困局的本质当AI服务器机架功率突破30kW门槛时,传统风冷系统开始面临物理极限。我曾亲眼见证某金融数据中心在部署GPU集群时,单机架功率密度达到42kW后出现的局部热点问题——温度传感器在3分钟内飙升12℃,导致服务器触发保护…

作者头像 李华
网站建设 2026/10/30 9:46:58

曦索X302荣获2026国芯展创新成果奖,沐曦股份持续拓展AI4S创新版图

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华
网站建设 2026/10/30 9:36:15

大规模MIMO LS信道估计MATLAB代码详解与避坑实践

简介:面向大规模MIMO系统研究的LS信道估计算法Matlab仿真实例,核心解决多天线场景下信道状态信息获取问题,适合无线通信方向高年级本科生与研究生对照学习,也适合作为课程设计或毕业设计的前期验证工具。资源包共10个文件&#xf…

作者头像 李华