13.函数的定义与调用

13.函数的定义与调用

欢迎来到《10天学会Python》第7天!今天学习函数——Python中的“代码打包术”,像是厨房里的多功能料理机,准备好食材(参数),按下按钮(调用),就能得到美味佳肴(结果)。

核心概念

函数是封装好的代码块,用来完成特定任务。学会函数后,你可以避免重复代码、分工明确、易于维护。

生活化比喻

想象函数就像厨房里的多功能料理机

  • 定义函数 = 购买料理机,了解它能做什么
  • 调用函数 = 放入食材(参数),按下按钮(调用),得到结果
  • 重复使用 = 随时榨果汁、磨豆浆,不用每次都买新机器

函数基本语法

1. 函数定义

使用 def 关键字定义函数:

python

def 函数名(参数):
    """函数说明文档"""
    函数体
    return 返回值  # 可选

2. 函数调用

定义函数后,通过函数名加括号调用:

python

函数名(实际参数)

代码示例(5个生活场景)

示例1:简单的问候函数

接收名字参数,返回问候语:

python

def greet(name):
    """向指定的人问好"""
    return f"你好,{name}!今天过得怎么样?"

message = greet("小明")
print(message)  # 你好,小明!今天过得怎么样?

示例2:使用内置函数

Python自带许多实用内置函数,无需定义直接使用:

python

fruits = ["苹果", "香蕉", "橙子"]
fruit_count = len(fruits)  # 3

scores = [85, 92, 78, 95]
highest = max(scores)  # 95

print(f"水果种类:{fruit_count}种,最高分:{highest}")

示例3:多个参数的函数

就像点餐需要菜品和数量:

python

def calculate_total(price, quantity, discount=0):
    """计算商品总价"""
    total = price * quantity * (1 - discount/100)
    return total

apple_total = calculate_total(8.5, 3)  # 25.5元
banana_total = calculate_total(6.0, 2, 10)  # 10.8元(9折后)

示例4:无参数函数

有些函数不需要外部输入,直接执行固定任务:

python

def show_menu():
    """显示餐厅菜单"""
    print("今日菜单:番茄炒蛋 25元,宫保鸡丁 38元")

show_menu()

示例5:函数嵌套调用

函数可以调用其他函数,就像流水线作业:

python

def get_average(scores):
    """计算平均分"""
    return sum(scores) / len(scores)

def get_grade(average_score):
    """根据平均分给出等级"""
    if average_score >= 90: return "A"
    elif average_score >= 80: return "B"
    elif average_score >= 70: return "C"
    elif average_score >= 60: return "D"
    else: return "F"

student_scores = [85, 92, 78, 88]
avg = get_average(student_scores)
grade = get_grade(avg)
print(f"平均分:{avg:.1f},等级:{grade}")  # 平均分:85.8,等级:B

函数执行流程

通过一个例子理解函数如何工作:

python

def make_juice(fruit, amount):
    print(f"开始榨{amount}杯{fruit}汁...")
    return f"{amount}杯{fruit}汁"

result = make_juice("橙子", 2)
print(f"完成:{result}")

执行步骤

  1. 程序遇到函数调用,传递参数
  2. 跳到函数定义处,执行函数体内代码
  3. 遇到 return 返回结果,回到调用处继续执行

实践应用:智能计算器

综合运用函数,制作一个简易计算器:

python

def add(a, b): return a + b
def subtract(a, b): return a - b
def multiply(a, b): return a * b

def divide(a, b):
    if b == 0: return "错误:除数不能为零"
    return a / b

def calculator(num1, num2, operation):
    if operation == "+": return add(num1, num2)
    elif operation == "-": return subtract(num1, num2)
    elif operation == "*": return multiply(num1, num2)
    elif operation == "/": return divide(num1, num2)
    else: return "错误:不支持的操作"

print(calculator(10, 5, "+"))   # 15

练习题

第1组:基础

  1. 两数之和:编写函数 add_two_numbers(a, b),返回两个数的和
    python

    # 示例调用
    result = add_two_numbers(5, 3)  # 应该返回8
    
  2. 三数平均值:编写函数 average_of_three(a, b, c),返回三个数的平均值
    python

    result = average_of_three(10, 20, 30)  # 应该返回20.0
    

第2组:应用

  1. 偶数判断:编写函数 is_even(number),判断一个数是否为偶数,返回布尔值
    python

    print(is_even(4))   # True
    print(is_even(7))   # False
    
  2. 成绩等级:编写函数 get_grade(score),根据分数返回等级(A:90+,B:80-89,C:70-79,D:60-69,F:<60)
    python

    print(get_grade(85))  # B
    

第3组:综合

  1. 阶乘计算:编写函数 factorial(n),计算n的阶乘,处理边界情况(n=0返回1,负数返回"无效输入")
    python

    print(factorial(5))   # 120
    print(factorial(0))   # 1
    
  2. 购物车计算:编写函数 calculate_cart(items),参数items是字典列表,计算总价
    python

    cart = [
        {"price": 8.5, "quantity": 2},
        {"price": 6.0, "quantity": 3}
    ]
    total = calculate_cart(cart)  # 8.5×2 + 6.0×3 = 35.0
    

总结

函数是Python编程的重要里程碑,掌握函数后你就能封装代码、提高效率、实现代码复用。

记住函数三要素:定义、调用、返回值

明天学习函数参数与返回值的更多用法,让你的函数更灵活强大!


学习建议

  1. 从解决小问题开始定义函数
  2. 多使用内置函数,减少重复代码
  3. 为函数起有意义的名字
12.字符串操作 2026-01-21
14.函数参数与返回值 2026-01-21

评论区