一、什么是函数?
想象你有一个智能榨汁机:放入水果→按下开关→获得果汁。在Python中,函数就像这个榨汁机——接收输入(参数),执行特定操作,返回结果。我们把重复使用的代码块封装成函数,需要时调用即可。
二、函数基础结构
# 定义函数
def make_juice(fruit, amount=2): # 参数:fruit必填,amount默认2个
"""制作果汁的函数说明""" # 文档字符串
juice = f"{amount}个{fruit}榨的汁"
return juice # 返回结果
# 调用函数
print(make_juice('苹果')) # 输出:2个苹果榨的汁
print(make_juice('橙子', 3)) # 输出:3个橙子榨的汁
三、参数详解
1. 位置参数 vs 关键字参数
def register(name, age, city):
print(f"{name}, {age}岁, 来自{city}")
register("张三", 25, "北京") # 正确顺序
register(city="上海", name="李四", age=30) # 关键字指定参数
2. 默认参数陷阱
# 错误示例:默认参数使用可变对象
def add_item(item, cart=[]):
cart.append(item)
return cart
print(add_item('苹果')) # ['苹果']
print(add_item('香蕉')) # ['苹果', '香蕉'] → 列表被共享!
# 正确写法
def add_item(item, cart=None):
if cart is None:
cart = []
cart.append(item)
return cart
四、返回值处理
1. 多值返回
def calculate_bmi(weight, height):
bmi = weight / (height ** 2)
if bmi < 18.5:
status = "偏轻"
elif 18.5 <= bmi < 24:
status = "正常"
else:
status = "超重"
return bmi, status # 实际返回元组
result = calculate_bmi(70, 1.75)
print(f"BMI值:{result[0]},状态:{result[1]}")
五、变量作用域
total = 0 # 全局变量
def update_total(amount):
global total # 声明使用全局变量
total += amount
print(f"当前总计:{total}")
update_total(100) # 当前总计:100
update_total(50) # 当前总计:150
六、lambda匿名函数
# 传统函数
def square(x):
return x ** 2
# lambda等效写法
square = lambda x: x ** 2
# 实际应用场景:排序
students = [
('王五', 88),
('赵六', 92),
('陈七', 85)
]
students.sort(key=lambda s: s[1], reverse=True)
print(students) # 按成绩降序排列
七、最佳实践原则
- 单一职责:每个函数只做一件事
# 不良示例
def process_data(data):
# 清洗数据
# 分析数据
# 生成报告
pass
# 优化版本
def clean_data(data): ...
def analyze_data(data): ...
def generate_report(analysis): ...
- 类型注解(Python 3.5+)
def greet(name: str, times: int = 1) -> str:
"""生成重复的问候语"""
return ("Hello " + name + "! ") * times
- 错误处理
def divide(a: float, b: float) -> float:
if b == 0:
raise ValueError("除数不能为零")
return a / b
八、综合案例:智能咖啡机
def make_coffee(coffee_type="美式", size="中杯", sugar=0):
"""制作咖啡的完整示例"""
menu = {
"美式": 15,
"拿铁": 20,
"卡布奇诺": 22
}
size_factor = {
"小杯": 0.8,
"中杯": 1,
"大杯": 1.2
}
if coffee_type not in menu:
available = ", ".join(menu.keys())
raise ValueError(f"可选咖啡:{available}")
base_price = menu[coffee_type] * size_factor.get(size, 1)
total = base_price + sugar * 0.5
recipe = f"制作{size}{coffee_type}"
if sugar > 0:
recipe += f",加{sugar}包糖"
return {
"recipe": recipe + "!",
"price": round(total, 1)
}
order = make_coffee("拿铁", "大杯", sugar=2)
print(f"{order['recipe']} 价格:{order['price']}元")
# 输出:制作大杯拿铁,加2包糖! 价格:25.4元
九、调试技巧
1.使用print
调试:
def complex_calculation(a, b):
print(f"输入参数:a={a}, b={b}") # 调试输出
result = (a ** 2 + b ** 2) ** 0.5
print(f"计算结果:{result}") # 调试输出
return result
2.使用断点调试(VSCode/PyCharm的调试模式)
总结
函数是Python编程的基石,掌握函数相当于获得代码复用的超能力。记住:
-
用函数封装重复逻辑
-
参数设计要清晰
-
注意作用域问题
-
保持函数功能单一
-
善用类型注解和文档字符串
试着把日常任务函数化,比如写一个自动整理文件的函数,或者处理Excel数据的函数,在实践中不断提升!