上一篇
Python函数(function)完全使用教程 | 从基础到实践
- Python
- 2025-07-25
- 1258
Python函数(function)完全使用教程
函数是Python编程中的核心概念之一,它允许你将代码组织成可重用的模块。本教程将带你全面了解Python函数的定义、使用和各种高级特性。
一、什么是Python函数?
函数是一段可重复使用的代码块,它接受输入(参数),执行特定任务,并返回结果。使用函数可以:
- 提高代码重用性
- 使程序模块化
- 简化复杂任务
- 提高代码可读性
二、定义和调用函数
1. 基本函数定义
使用def
关键字定义函数:
# 定义一个简单的函数 def greet(name): """打印问候语""" print(f"你好, {name}!") # 调用函数 greet("张三") # 输出: 你好, 张三!
2. 函数结构解析
def
:定义函数的关键字greet
:函数名(应使用小写字母和下划线)(name)
:参数列表- 三引号字符串:文档字符串(docstring),描述函数功能
- 函数体:缩进的代码块
三、函数参数详解
1. 位置参数
最常见的参数类型,按位置顺序传递:
def describe_pet(animal_type, pet_name): print(f"\n我有一只{animal_type}。") print(f"我的{animal_type}叫{pet_name}。") describe_pet('狗', '旺财')
2. 关键字参数
直接指定参数名,不依赖顺序:
describe_pet(pet_name='旺财', animal_type='狗')
3. 默认参数
为参数提供默认值:
def describe_pet(pet_name, animal_type='狗'): print(f"\n我有一只{animal_type}。") print(f"我的{animal_type}叫{pet_name}。") describe_pet(pet_name='旺财') # 使用默认的animal_type='狗'
4. 可变参数(*args和**kwargs)
处理不确定数量的参数:
# *args 接收任意数量的位置参数 def sum_numbers(*args): total = 0 for num in args: total += num return total print(sum_numbers(1, 2, 3)) # 输出: 6 # **kwargs 接收任意数量的关键字参数 def build_profile(**kwargs): profile = {} for key, value in kwargs.items(): profile[key] = value return profile user = build_profile(name='张三', age=30, city='北京') print(user) # 输出: {'name': '张三', 'age': 30, 'city': '北京'}
四、返回值
使用return
语句返回结果:
def get_formatted_name(first_name, last_name): """返回整洁的姓名""" full_name = f"{first_name} {last_name}" return full_name.title() musician = get_formatted_name('jimi', 'hendrix') print(musician) # 输出: Jimi Hendrix
函数可以返回多个值(实际上是元组):
def calculate(x, y): add = x + y subtract = x - y multiply = x * y divide = x / y return add, subtract, multiply, divide results = calculate(10, 5) print(results) # 输出: (15, 5, 50, 2.0)
五、作用域
Python中有两种作用域:
1. 局部变量
函数内部定义的变量,只在函数内部有效
2. 全局变量
函数外部定义的变量,在整个程序中都有效
x = 10 # 全局变量 def my_function(): y = 5 # 局部变量 global x x = 20 # 修改全局变量 my_function() print(x) # 输出: 20 print(y) # 报错: NameError: name 'y' is not defined
六、Lambda函数
Lambda函数是一种小型匿名函数,用于简单操作:
# 语法: lambda arguments: expression square = lambda x: x ** 2 print(square(5)) # 输出: 25 # 与map()函数配合使用 numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers)) print(squared) # 输出: [1, 4, 9, 16, 25] # 与filter()函数配合使用 even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # 输出: [2, 4]
七、函数最佳实践
- 命名规范:使用小写字母和下划线(snake_case)
- 函数长度:尽量保持函数简短(不超过20行)
- 单一职责:一个函数只做一件事
- 文档字符串:为每个函数添加说明
- 避免全局变量:尽量使用参数和返回值
- 类型提示(Python 3.5+):提高代码可读性
def calculate_circle_area(radius: float) -> float: """计算圆的面积 参数: radius (float): 圆的半径 返回: float: 圆的面积 """ PI = 3.14159 return PI * radius ** 2 print(calculate_circle_area(5)) # 输出: 78.53975
总结
函数是Python编程的基石,掌握函数的定义、参数传递、作用域和高级用法对于编写高效、可维护的代码至关重要。本教程涵盖了Python函数的所有核心概念,通过实际代码示例展示了各种用法。多加练习,你将能够灵活运用函数来构建更复杂的程序!
本文由SongSenNen于2025-07-25发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://521pj.cn/20256455.html
发表评论