
前两篇介绍了Python的基础语法和核心数据结构。本篇将深入讲解函数的高级用法以及如何读写文件——程序与外部世界交互的基础。一、函数参数与返回值1.1 位置参数与关键字参数函数定义时声明参数调用时可按位置传递也可按关键字传递。pythondef introduce(name, age, city北京): # 带默认值的参数必须放在最后 print(f{name}{age}岁来自{city}) introduce(张三, 25) # 位置参数 introduce(name李四, age30) # 关键字参数 introduce(王五, city上海, age28) # 混合位置参数在前1.2 可变参数不确定参数个数时使用可变参数。pythondef sum_all(*args): 接收任意数量的位置参数返回它们的和 total 0 for num in args: total num return total print(sum_all(1, 2, 3)) # 6 print(sum_all(10, 20, 30, 40)) # 100 def show_info(**kwargs): 接收任意数量的关键字参数 for key, value in kwargs.items(): print(f{key}: {value}) show_info(nameAlice, age25, jobEngineer)1.3 参数解包使用*和**在调用时解包序列和字典。pythonnumbers [1, 2, 3] print(sum_all(*numbers)) # 列表解包为位置参数 person {name: Bob, age: 30, city: 上海} show_info(**person) # 字典解包为关键字参数1.4 作用域规则函数内部可以访问外部变量但修改需要声明。pythonx 10 def func(): print(x) # 可以读取外部变量 def modify(): global x # 声明使用全局变量 x 20 modify() print(x) # 20nonlocal关键字用于嵌套函数中修改外层函数的变量。pythondef outer(): count 0 def inner(): nonlocal count count 1 return count return inner二、匿名函数lambdalambda函数是单行表达式适合作为参数传递给其他函数。pythonsquare lambda x: x ** 2 print(square(5)) # 25 # 在排序中使用 names [Alice, Bob, Charlie, David] names.sort(keylambda name: len(name)) print(names) # [Bob, Alice, David, Charlie] # 在map/filter中使用 numbers [1, 2, 3, 4, 5] squared list(map(lambda x: x**2, numbers)) evens list(filter(lambda x: x % 2 0, numbers))三、文件操作基础3.1 打开与关闭文件使用open()打开文件返回文件对象。操作完成后必须调用close()关闭。pythonf open(data.txt, r) # 读取模式 content f.read() f.close()使用with语句可以自动关闭文件是推荐的做法。pythonwith open(data.txt, r) as f: content f.read() # 离开with块后自动关闭3.2 文件读写模式模式说明r只读文件必须存在w写入文件不存在则创建存在则覆盖a追加文件不存在则创建r读写文件必须存在b二进制模式如rb、wb3.3 读取文件的方法pythonwith open(data.txt, r) as f: # 一次性读取全部内容 content f.read() # 按行读取 lines f.readlines() # 返回列表每行一个元素 # 逐行遍历 for line in f: print(line.strip())3.4 写入文件pythonwith open(output.txt, w) as f: f.write(第一行内容\n) f.write(第二行内容\n) with open(output.txt, a) as f: f.write(追加的内容\n)四、异常处理程序运行过程中会出现错误如文件不存在、类型转换失败异常处理机制可以让程序优雅地处理这些情况。4.1 try/except/else/finallypythontry: n int(input(请输入数字)) result 10 / n except ValueError: print(请输入有效的数字) except ZeroDivisionError: print(除数不能为零) except Exception as e: # 捕获其他所有异常 print(f发生错误{e}) else: print(f计算结果{result}) # 没有异常时执行 finally: print(无论是否出错都会执行) # 释放资源等清理工作4.2 自定义异常使用raise主动抛出异常也可以继承Exception创建自定义异常。pythondef withdraw(amount, balance): if amount balance: raise ValueError(余额不足) return balance - amount try: withdraw(100, 50) except ValueError as e: print(e)五、模块与导入模块是包含Python代码的文件.py文件是组织代码的基本单位。python# 导入整个模块 import math print(math.sqrt(16)) # 导入特定函数 from math import sqrt, pi print(sqrt(25)) # 导入并起别名 import datetime as dt print(dt.datetime.now()) # 导入所有内容一般不推荐因为可能覆盖已有变量名 from math import * print(sin(0))5.1if __name__ __main__当模块被直接运行时__name__值为__main__当被导入时__name__是模块名。这个特性允许同一文件既作为脚本运行也作为模块被导入。pythondef add(a, b): return a b if __name__ __main__: # 只有直接运行时才执行测试代码 print(add(3, 5)) # 8 print(add(10, 20)) # 30六、小结本篇介绍了函数的高级用法可变参数、解包、作用域、文件操作和异常处理。掌握这些内容程序就能与外部世界交互处理各种运行时错误。下一篇将介绍面向对象编程这是组织大型程序的核心思想。