资讯详情

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

📅 2026/10/30 9:58:41 | 华诺云谱 👁 阅读
第三篇:函数、文件与异常处理 / 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.pythondef greet(name, greetingHello): 返回问候语 / Return a greeting message. return f{greeting}, {name}! print(greet(Alice)) # Hello, Alice! print(greet(Bob, greeting你好)) # 你好, Bob! print(greet(nameCarol, greetingHi)) # 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.pythondef summarize(*args, **kwargs): print(位置参数 / positional:, args) print(关键字参数 / keyword:, kwargs) summarize(1, 2, 3, nameAlice, age20) # 位置参数 / 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)) # 73.3 读写文件 / Reading and Writing Files中文用with open(...) as f打开文件代码块结束时自动关闭。encodingutf-8处理中文必须显式指定。English: Usewith open(...) as fto open files; they close automatically when the block ends. Always specifyencodingutf-8for Chinese text.python# 写入文件 / write to file with open(demo.txt, w, encodingutf-8) as f: f.write(第一行 / line one\n) f.write(第二行 / line two\n) # 读取整个文件 / read entire file with open(demo.txt, r, encodingutf-8) as f: content f.read() print(content) # 逐行读取 / read line by line with open(demo.txt, r, encodingutf-8) as f: for line_num, line in enumerate(f, start1): 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.pythondef 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)) # None3.5 自定义异常 / Custom Exceptions中文继承Exception定义业务异常便于上层代码精确捕获。English: SubclassExceptionto define business-specific errors that callers can catch precisely.pythonclass InsufficientBalanceError(Exception): 余额不足异常 / Raised when balance is insufficient. pass def withdraw(balance, amount): if amount balance: raise InsufficientBalanceError( f余额 {balance} 不足以取出 {amount} / fbalance {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 doesnt exist.pythondef analyze_file(path): 统计文件行数与字符数 / Count lines and characters. try: with open(path, r, encodingutf-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
📝

华诺云谱内容团队

资深建站顾问 · 行业研究员

10年+企业数字化服务经验,专注智能建站、SEO优化与品牌营销,持续输出建站技巧、行业洞察与营销干货,已帮助5000+企业实现数字化增长。

你可能需要的服务

订阅华诺云谱资讯周报

每周一封,精选建站技巧、SEO与营销干货,直达邮箱。已有 8,000+ 企业主订阅,助你少走弯路。

↑