Day 3 · 函数定义、参数与 Lambda

Week 1 · Day 3 / 56 · 预计 1.5-2 小时 · 返回大纲

一、函数定义基础

JavaScript
// 函数声明
function greet(name) {
    return `Hello, ${name}!`;
}

// 函数表达式
const greet = function(name) {
    return `Hello, ${name}!`;
};

// 箭头函数
const greet = (name) => `Hello, ${name}!`;
Python
# 函数定义
def greet(name):
    return f"Hello, {name}!"

# Python 没有函数表达式或箭头函数的概念
# 但可以用 lambda(后面讲)
关键差异:

函数调用

def greet(name):
    return f"Hello, {name}!"

# 调用
greet("Alice")           # "Hello, Alice!"

# 函数是对象,可以赋值
say_hello = greet
say_hello("Bob")         # "Hello, Bob!"

# 查看函数信息
greet.__name__           # "greet"
type(greet)              # <class 'function'>

二、参数详解

2.1 位置参数

def add(a, b):
    return a + b

add(1, 2)        # 3
add("1", "2")    # "12"(字符串拼接)

2.2 默认参数

JavaScript
function greet(name, greeting = "Hello") {
    return `${greeting}, ${name}!`;
}

greet("Alice");           // "Hello, Alice!"
greet("Alice", "Hi");     // "Hi, Alice!"
Python
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

greet("Alice")            # "Hello, Alice!"
greet("Alice", "Hi")      # "Hi, Alice!"
greet("Alice", greeting="Hey")  # "Hey, Alice!"
⚠️ 经典坑:默认参数不要是可变对象
# 错误示范
def add_item(item, items=[]):
    items.append(item)
    return items

add_item(1)    # [1]
add_item(2)    # [1, 2]  ← 不是 [2]!因为 [] 只创建一次

# 正确写法
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

2.3 关键字参数

def create_user(name, age, city="未知", active=True):
    return {
        "name": name,
        "age": age,
        "city": city,
        "active": active
    }

# 位置传参
create_user("Alice", 25)

# 关键字传参(顺序无关)
create_user(name="Alice", age=25)
create_user(age=25, name="Alice")  # 也可以

# 混合使用(位置参数必须在关键字参数前面)
create_user("Alice", age=25, city="北京")

2.4 *args 和 **kwargs

JavaScript
// 剩余参数
function sum(...numbers) {
    return numbers.reduce((a, b) => a + b, 0);
}

sum(1, 2, 3);  // 6

// 对象展开
const defaults = { a: 1, b: 2 };
const options = { ...defaults, c: 3 };
Python
# *args:收集位置参数为元组
def sum(*numbers):
    return sum(numbers)

sum(1, 2, 3)  # 6

# **kwargs:收集关键字参数为字典
def print_info(**info):
    for key, value in info.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25)
# name: Alice
# age: 25
# 混合使用
def func(a, b, *args, **kwargs):
    print(f"a={a}, b={b}")
    print(f"args={args}")      # 额外位置参数
    print(f"kwargs={kwargs}")  # 额外关键字参数

func(1, 2, 3, 4, 5, x=10, y=20)
# a=1, b=2
# args=(3, 4, 5)
# kwargs={'x': 10, 'y': 20}

# 解包调用
def greet(name, greeting):
    return f"{greeting}, {name}!"

args = ("Alice", "Hello")
greet(*args)           # 相当于 greet("Alice", "Hello")

kwargs = {"name": "Bob", "greeting": "Hi"}
greet(**kwargs)        # 相当于 greet(name="Bob", greeting="Hi")

2.5 参数顺序规则

def func(a, b=2, *args, **kwargs):
    pass

# 正确顺序:
# 1. 位置参数
# 2. 默认参数
# 3. *args
# 4. **kwargs

三、返回值

# 返回单个值
def add(a, b):
    return a + b

# 返回多个值(实际是元组)
def get_user():
    return "Alice", 25, "北京"

name, age, city = get_user()
print(name)  # Alice

# 不带 return 或 return 无值,返回 None
def no_return():
    pass

result = no_return()
print(result)  # None

# 提前返回
def check_age(age):
    if age < 0:
        return "年龄不能为负"
    if age < 18:
        return "未成年"
    return "成年"

四、Lambda 表达式

JavaScript 箭头函数
// 单行
const add = (a, b) => a + b;

// 多行
const add = (a, b) => {
    const result = a + b;
    return result;
};

// 作为参数
[1, 2, 3].map(x => x * 2);
[1, 2, 3].filter(x => x > 1);
[1, 2, 3].reduce((a, b) => a + b);
Python Lambda
# lambda 只能写单行表达式
add = lambda a, b: a + b

# 不能写多行,不能写语句
# 这是限制,不是 bug

# 作为参数
list(map(lambda x: x * 2, [1, 2, 3]))
list(filter(lambda x: x > 1, [1, 2, 3]))

# 但通常用列表推导式更 Pythonic
[x * 2 for x in [1, 2, 3]]
[x for x in [1, 2, 3] if x > 1]
Pythonic 建议:
# lambda 常见用法:排序
students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 92},
    {"name": "Charlie", "score": 78},
]

# 按分数排序
sorted(students, key=lambda s: s["score"])

# 按名字排序
sorted(students, key=lambda s: s["name"])

# 降序
sorted(students, key=lambda s: s["score"], reverse=True)

五、文档字符串(Docstring)

def calculate_bmi(weight, height):
    """
    计算 BMI 指数。
    
    Args:
        weight: 体重(千克)
        height: 身高(米)
    
    Returns:
        BMI 值,保留一位小数
    
    Examples:
        >>> calculate_bmi(70, 1.75)
        22.9
    """
    bmi = weight / (height ** 2)
    return round(bmi, 1)

# 查看文档
print(calculate_bmi.__doc__)
help(calculate_bmi)

六、函数作为参数

def apply_operation(x, y, operation):
    """对 x 和 y 应用 operation"""
    return operation(x, y)

def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

# 传递函数
apply_operation(3, 4, add)       # 7
apply_operation(3, 4, multiply)  # 12

# 传递 lambda
apply_operation(3, 4, lambda a, b: a ** b)  # 81

七、实战:Todo 任务管理器(函数版)

创建 day3.py:

#!/usr/bin/env python3
"""Day 3 练习:Todo 任务管理器"""

# 任务存储
tasks = []

def add_task(title, priority="medium"):
    """添加任务"""
    task = {
        "id": len(tasks) + 1,
        "title": title,
        "priority": priority,
        "done": False
    }
    tasks.append(task)
    return task

def list_tasks(show_done=False):
    """列出任务"""
    for task in tasks:
        if not show_done and task["done"]:
            continue
        status = "✓" if task["done"] else "○"
        print(f"{status} [{task['id']}] {task['title']} ({task['priority']})")

def complete_task(task_id):
    """完成任务"""
    for task in tasks:
        if task["id"] == task_id:
            task["done"] = True
            return True
    return False

def delete_task(task_id):
    """删除任务"""
    for i, task in enumerate(tasks):
        if task["id"] == task_id:
            tasks.pop(i)
            return True
    return False

def show_menu():
    """显示菜单"""
    print("\n" + "=" * 30)
    print("Todo 任务管理器")
    print("=" * 30)
    print("1. 添加任务")
    print("2. 查看任务")
    print("3. 完成任务")
    print("4. 删除任务")
    print("5. 查看全部(含已完成)")
    print("0. 退出")
    print("=" * 30)

def main():
    while True:
        show_menu()
        choice = input("请选择:")
        
        if choice == "1":
            title = input("任务标题:")
            priority = input("优先级 (high/medium/low,默认 medium):") or "medium"
            add_task(title, priority)
            print("任务已添加")
        
        elif choice == "2":
            list_tasks()
        
        elif choice == "3":
            task_id = int(input("任务 ID:"))
            if complete_task(task_id):
                print("任务已完成")
            else:
                print("任务不存在")
        
        elif choice == "4":
            task_id = int(input("任务 ID:"))
            if delete_task(task_id):
                print("任务已删除")
            else:
                print("任务不存在")
        
        elif choice == "5":
            list_tasks(show_done=True)
        
        elif choice == "0":
            print("再见!")
            break
        
        else:
            print("无效选择")

if __name__ == "__main__":
    main()

八、动手练习

练习 1:温度转换器
编写摄氏度和华氏度互转的函数
# 要求:
# 1. celsius_to_fahrenheit(c):摄氏度转华氏度,公式 F = C * 9/5 + 32
# 2. fahrenheit_to_celsius(f):华氏度转摄氏度,公式 C = (F - 32) * 5/9
# 3. 保留 1 位小数
# 4. 写 docstring

# 你的代码:
查看答案
参考答案
def celsius_to_fahrenheit(c):
    """
    摄氏度转华氏度。
    
    Args:
        c: 摄氏度
    
    Returns:
        华氏度,保留 1 位小数
    """
    return round(c * 9 / 5 + 32, 1)

def fahrenheit_to_celsius(f):
    """
    华氏度转摄氏度。
    
    Args:
        f: 华氏度
    
    Returns:
        摄氏度,保留 1 位小数
    """
    return round((f - 32) * 5 / 9, 1)

# 测试
print(celsius_to_fahrenheit(25))    # 77.0
print(fahrenheit_to_celsius(77))    # 25.0
练习 2:学生成绩统计
用 *args 接收任意数量成绩,返回统计信息
# 要求:
# 1. 函数名:analyze_scores
# 2. 接收任意数量的成绩(*args)
# 3. 返回字典:平均分、最高分、最低分、及格人数(>=60)
# 4. 保留 1 位小数

# 你的代码:
查看答案
参考答案
def analyze_scores(*scores):
    """分析成绩统计"""
    if not scores:
        return {"error": "没有成绩数据"}
    
    average = round(sum(scores) / len(scores), 1)
    highest = max(scores)
    lowest = min(scores)
    passed = sum(1 for s in scores if s >= 60)
    
    return {
        "average": average,
        "highest": highest,
        "lowest": lowest,
        "passed": passed,
        "total": len(scores)
    }

# 测试
result = analyze_scores(85, 92, 78, 90, 45, 88)
print(result)
# {'average': 79.7, 'highest': 92, 'lowest': 45, 'passed': 5, 'total': 6}
练习 3:用户信息构建器
用 **kwargs 构建用户信息字典
# 要求:
# 1. 函数名:build_profile
# 2. 必选参数:first_name, last_name
# 3. 可选:任意用户信息(**kwargs),如 age, city, email 等
# 4. 返回完整用户信息字典

# 你的代码:
查看答案
参考答案
def build_profile(first_name, last_name, **info):
    """构建用户信息"""
    profile = {
        "first_name": first_name,
        "last_name": last_name,
        "full_name": f"{first_name} {last_name}"
    }
    profile.update(info)
    return profile

# 测试
user = build_profile("三", "张", age=25, city="北京", job="工程师")
print(user)
# {'first_name': '三', 'last_name': '张', 'full_name': '三 张', 
#  'age': 25, 'city': '北京', 'job': '工程师'}
练习 4:排序练习
用 lambda 对复杂列表排序
products = [
    {"name": "iPhone", "price": 5999, "stock": 10},
    {"name": "iPad", "price": 3999, "stock": 5},
    {"name": "MacBook", "price": 9999, "stock": 3},
    {"name": "AirPods", "price": 1299, "stock": 20},
]

# 要求:
# 1. 按价格从低到高排序
# 2. 按库存从高到低排序
# 3. 按名称字母顺序排序
# 4. 找出价格最贵的商品
# 5. 用 lambda + sorted/max 实现

# 你的代码:
查看答案
参考答案
products = [
    {"name": "iPhone", "price": 5999, "stock": 10},
    {"name": "iPad", "price": 3999, "stock": 5},
    {"name": "MacBook", "price": 9999, "stock": 3},
    {"name": "AirPods", "price": 1299, "stock": 20},
]

# 1. 按价格从低到高
by_price = sorted(products, key=lambda p: p["price"])
print("按价格排序:", [p["name"] for p in by_price])

# 2. 按库存从高到低
by_stock = sorted(products, key=lambda p: p["stock"], reverse=True)
print("按库存排序:", [p["name"] for p in by_stock])

# 3. 按名称字母顺序
by_name = sorted(products, key=lambda p: p["name"])
print("按名称排序:", [p["name"] for p in by_name])

# 4. 最贵的商品
most_expensive = max(products, key=lambda p: p["price"])
print(f"最贵商品:{most_expensive['name']},价格 {most_expensive['price']}")

九、打卡验收

会用 def 定义函数,理解函数是对象
掌握默认参数,知道不要用可变对象做默认值
会用 *args 和 **kwargs 收集参数
理解参数顺序:位置参数 → 默认参数 → *args → **kwargs
会用 lambda 写简单函数,知道其限制
会写 docstring 文档字符串
理解函数可以作为参数传递
完成 4 个动手练习,代码能跑通
打卡方式: 全部勾选后,告诉我 "Day 3 打卡",并贴出你的代码,我帮你检查。
明天预告(Day 4): 列表、元组、集合、字典详解,列表推导式(Python 核心特性)。