第32集:函数参数——位置参数

学习目标

  • 理解位置参数的概念
  • 掌握位置参数的传递规则
  • 学会处理多个位置参数
  • 了解位置参数的注意事项

一、什么是位置参数?

位置参数是指在调用函数时,参数按照定义的顺序依次传递的参数。

核心特点

  • 顺序重要:参数的传递顺序必须与函数定义的顺序一致
  • 数量匹配:传递的参数数量必须与定义的参数数量相同
  • 一对一对应:第1个实参传递给第1个形参,第2个传递给第2个,以此类推

生活类比

  • 点餐时说"我要一杯咖啡,加糖":咖啡是第1个,糖是第2个
  • 如果说"加糖,一杯咖啡"就可能导致误解
  • 这就是位置参数的顺序问题

二、位置参数的基本语法

函数定义

def 函数名(参数1, 参数2, 参数3, ...):
    函数体
    ...

函数调用

函数名(值1, 值2, 值3, ...)
定义时 调用时 说明
def func(a, b): func(1, 2) a=1, b=2
def func(x, y, z): func(10, 20, 30) x=10, y=20, z=30

三、基础示例

示例1:最简单的位置参数

def greet(name, message):
    """向某人发送问候消息"""
    print(f"{name},{message}")

# 调用函数 - 位置对应
greet("小明", "早上好!")     # 输出:小明,早上好!
greet("小红", "欢迎光临!")   # 输出:小红,欢迎光临!

示例2:数学运算函数

def add(a, b):
    """计算两个数的和"""
    return a + b

result = add(10, 20)  # a=10, b=20
print(result)  # 输出:30

示例3:多个参数的函数

def introduce(name, age, city, hobby):
    """自我介绍"""
    print(f"我叫{name},今年{age}岁")
    print(f"住在{city},喜欢{hobby}")

# 调用函数
introduce("小王", 25, "北京", "编程")
# 输出:
# 我叫小王,今年25岁
# 住在北京,喜欢编程

四、位置参数的传递规则

规则1:顺序必须一致

def calculate_price(price, quantity, discount):
    """计算最终价格"""
    final_price = price * quantity * (1 - discount)
    return final_price

# ✅ 正确调用
result1 = calculate_price(100, 2, 0.1)
print(result1)  # 输出:180.0 (100*2*0.9)

规则2:参数数量必须匹配

def show_info(name, age):
    """显示信息"""
    print(f"姓名:{name},年龄:{age}")

# ✅ 正确调用
show_info("小李", 20)

# ❌ 错误调用:参数太少
# show_info("小李")  # 报错

# ❌ 错误调用:参数太多
# show_info("小李", 20, "北京")  # 报错

规则3:参数类型不强制但建议匹配

def multiply(a, b):
    """两个数相乘"""
    return a * b

# ✅ 数字相乘
print(multiply(3, 4))      # 输出:12

# ⚠️ 数字和字符串相乘(字符串重复)
print(multiply(3, "Hi"))   # 输出:HiHiHi
print(multiply("Hello", 2)) # 输出:HelloHello

# ⚠️ 列表重复
print(multiply([1, 2], 3))  # 输出:[1, 2, 1, 2, 1, 2]

五、实际应用示例

示例4:计算三角形面积

def triangle_area(base, height):
    """计算三角形面积"""
    area = 0.5 * base * height
    return area

area1 = triangle_area(10, 5)    # 底10,高5
print(f"三角形面积1:{area1}")  # 输出:25.0

area2 = triangle_area(6.5, 4.2)  # 底6.5,高4.2
print(f"三角形面积2:{area2}")  # 输出:13.65

示例5:计算BMI指数

def calculate_bmi(weight, height):
    """
    计算BMI指数
    
    参数:
        weight: 体重(公斤)
        height: 身高(米)
        
    返回:
        BMI值
    """
    bmi = weight / (height ** 2)
    return bmi

bmi = calculate_bmi(70, 1.75)
print(f"BMI指数:{bmi:.2f}")  # 输出:BMI指数:22.86

示例6:格式化日期

def format_date(year, month, day):
    """格式化日期"""
    return f"{year}年{month}月{day}日"

date1 = format_date(2024, 12, 25)
print(date1)  # 输出:2024年12月25日

date2 = format_date(2025, 1, 1)
print(date2)  # 输出:2025年1月1日

六、顺序的重要性

示例7:交换参数导致错误

def divide(numerator, denominator):
    """除法运算"""
    return numerator / denominator

# ✅ 正确调用
result1 = divide(10, 2)
print(f"10 ÷ 2 = {result1}")  # 输出:5.0

# ❌ 错误调用:参数顺序错误
result2 = divide(2, 10)
print(f"2 ÷ 10 = {result2}")  # 输出:0.2(不是期望的结果)

示例8:减法函数的参数顺序

def subtract(minuend, subtrahend):
    """
    减法运算
    
    参数:
        minuend: 被减数
        subtrahend: 减数
    """
    return minuend - subtrahend

# 注意参数的顺序
result1 = subtract(10, 3)  # 10 - 3 = 7
print(f"10 - 3 = {result1}")  # 输出:7

result2 = subtract(3, 10)  # 3 - 10 = -7
print(f"3 - 10 = {result2}")  # 输出:-7

七、处理多个位置参数

示例9:统计函数

def analyze_scores(name, score1, score2, score3, score4):
    """
    分析四个科目的成绩
    
    参数:
        name: 学生姓名
        score1, score2, score3, score4: 四科成绩
    """
    scores = [score1, score2, score3, score4]
    average = sum(scores) / len(scores)
    highest = max(scores)
    lowest = min(scores)
    
    print(f"\n学生:{name}")
    print(f"四科成绩:{scores}")
    print(f"平均分:{average:.1f}")
    print(f"最高分:{highest}")
    print(f"最低分:{lowest}")
    return average

# 调用函数
avg = analyze_scores("张三", 85, 92, 78, 88)

示例10:矩形信息函数

def rectangle_info(length, width):
    """输出矩形的各项信息"""
    area = length * width
    perimeter = 2 * (length + width)
    diagonal = (length ** 2 + width ** 2) ** 0.5
    
    print(f"\n矩形(长:{length},宽:{width})")
    print(f"面积:{area:.2f}")
    print(f"周长:{perimeter:.2f}")
    print(f"对角线长度:{diagonal:.2f}")

# 调用函数
rectangle_info(8, 5)
rectangle_info(12.5, 7.3)

八、常见错误与调试

错误1:参数顺序错误

def power(base, exponent):
    """计算幂运算"""
    return base ** exponent

# ❌ 想要计算2的10次方,但写反了
result = power(10, 2)  # 实际上是10的2次方 = 100

# ✅ 正确写法
result = power(2, 10)   # 2的10次方 = 1024

错误2:参数数量不匹配

def add_three(a, b, c):
    """计算三个数的和"""
    return a + b + c

# ❌ 参数不足
# add_three(1, 2)  # TypeError: add_three() missing 1 required positional argument

# ✅ 正确调用
add_three(1, 2, 3)

调试技巧:使用print查看参数值

def debug_function(a, b, c):
    """带调试信息的函数"""
    print(f"调试信息:a={a}, b={b}, c={c}")
    result = a + b + c
    return result

# 调用时可以清楚地看到参数的值
debug_function(10, 20, 30)

九、位置参数的优势

优势 说明
简洁 不需要指定参数名,代码更简洁
高效 参数传递速度快,性能好
直观 按顺序传递,易于理解
标准化 大多数库函数都使用位置参数

何时使用位置参数

  • 参数较少(通常3个以内)
  • 参数顺序有明确逻辑关系
  • 参数含义清晰不易混淆
  • 追求代码简洁性

十、实际项目中的应用

案例1:电商订单计算

def calculate_order_price(price, quantity, tax_rate, discount):
    """
    计算订单总价
    
    参数:
        price: 单价
        quantity: 数量
        tax_rate: 税率(如0.1表示10%)
        discount: 折扣(如0.05表示95折)
    """
    subtotal = price * quantity
    tax = subtotal * tax_rate
    after_discount = subtotal * (1 - discount)
    total = after_discount + tax
    
    return total

# 计算订单总价
order_total = calculate_order_price(100, 2, 0.1, 0.05)
print(f"订单总价:¥{order_total:.2f}")

案例2:游戏角色属性

def create_character(name, health, attack, defense):
    """
    创建游戏角色
    
    参数:
        name: 角色名
        health: 生命值
        attack: 攻击力
        defense: 防御力
    """
    character = {
        'name': name,
        'health': health,
        'attack': attack,
        'defense': defense
    }
    return character

# 创建角色
warrior = create_character("战士", 100, 50, 30)
mage = create_character("法师", 60, 80, 10)

print(f"角色1:{warrior}")
print(f"角色2:{mage}")

十一、小结

知识点 说明
位置参数 按顺序传递的参数
顺序重要 参数顺序必须与定义一致
数量匹配 传递的参数数量要正确
一一对应 第n个实参传给第n个形参
适用场景 参数少、顺序清晰的情况

十二、课后练习

练习1

定义函数rectangle_area(length, width),计算矩形面积。

练习2

定义函数circle_info(radius),计算圆的周长和面积。

练习3

定义函数compare_numbers(a, b),比较两个数的大小,返回较大的数。

练习4

定义函数print_person_info(name, age, gender, city),打印个人信息。

练习5

定义函数calculate_final_price(price, discount, tax),计算最终价格:

  • 先计算折扣:price × (1 - discount)
  • 再加税:折扣价 × (1 + tax)
« 上一篇 函数定义与调用 下一篇 » 函数参数-默认参数