一、函数的核心概念:什么是函数?

函数是一段可重复使用的组织好的代码块,用于执行一个特定的、相关的任务。

核心思想:

  • 封装(Encapsulation): 将复杂的操作细节隐藏起来,提供一个简单的接口(函数名和参数)。
  • 抽象(Abstraction): 使用者只需要知道函数的功能(做什么),而无需知道其内部实现(怎么做)。
  • 代码复用(Reusability): 避免编写重复的代码,提高开发效率和可维护性。

二、函数的定义与调用

1. 定义函数 (def)

使用 def 关键字来定义一个函数。

语法:

def function_name(parameters):
    """docstring"""  # 可选的文档字符串,用于说明函数的功能
    # 函数体:要执行的代码块
    # ...
    return result  # 可选的 return 语句,用于返回结果

示例:

def hello(name):
    """这是一个向用户问好的函数"""
    print(f"Hello, {name}! Welcome aboard.")

2. 调用函数 (function_name())

通过函数名后跟括号 () 来调用函数,括号内可以传递实际的值(称为实参)。

示例:

hello("Alice")  # 输出:Hello, Alice! Welcome aboard.
hello("Bob")    # 输出:Hello, Bob! Welcome aboard.

三、函数参数详解(重点与难点)

参数是函数与外部世界沟通的桥梁。Python 的函数参数非常灵活。

1. 参数类型

  • 形参(Formal Parameter): 定义函数时括号里的变量,如 def func(a, b) 中的 a 和 b
  • 实参(Actual Argument): 调用函数时传递给形参的具体值,如 func(1, 2) 中的 1 和 2

2. 传递实参的方式

  • 位置参数(Positional Arguments)
    实参的顺序必须与形参的顺序严格一致。
def describe_pet(animal_type, pet_name):
    print(f"I have a {animal_type}. Its name is {pet_name}.")

describe_pet('hamster', 'Harry') # 正确:animal_type='hamster', pet_name='Harry'
describe_pet('Harry', 'hamster') # 错误且逻辑混乱:animal_type='Harry', pet_name='hamster'
  • 关键字参数(Keyword Arguments)
    使用 形参=值 的形式传递实参,顺序无关紧要。
describe_pet(animal_type='hamster', pet_name='Harry') # 清晰
describe_pet(pet_name='Harry', animal_type='hamster') # 同样清晰且正确
  • 默认参数(Default Arguments)
    在定义函数时为形参指定一个默认值。调用时如果不提供该参数,则使用默认值。
    注意: 默认参数必须指向不可变对象(如 None, 数字, 字符串, 元组)。使用可变对象(如 []{})是常见的陷阱。
def describe_pet(pet_name, animal_type='dog'): # animal_type 有默认值
    print(f"I have a {animal_type}. Its name is {pet_name}.")

describe_pet('Willie')           # 输出:I have a dog. Its name is Willie.
describe_pet('Harry', 'hamster') # 输出:I have a hamster. Its name is Harry.

3. 高级参数类型(处理不定数量的参数)

  • 可变位置参数 (*args)
    收集所有未命名的位置参数到一个元组中。
def make_pizza(*toppings):
    """打印顾客点的所有配料"""
    print("Making a pizza with the following toppings:")
    for topping in toppings:
        print(f"- {topping}")

make_pizza('pepperoni')
make_pizza('mushrooms', 'peppers', 'extra cheese')
  • 可变关键字参数 (**kwargs)
    收集所有未命名的关键字参数到一个字典中。
def build_profile(first, last, **user_info):
    """创建一个包含用户所有信息的字典"""
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info

user_profile = build_profile('albert', 'einstein',
                             location='princeton',
                             field='physics')
print(user_profile)
# 输出:{'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}

组合使用顺序(非常重要!):
在定义函数时,参数必须按以下顺序声明:
def func(positional_args, default_args, *args, **kwargs)


四、返回值 (return)

return 语句用于结束函数的执行,并可选地将一个值返回给调用者。

  • 函数可以没有 return 语句,执行完毕后会隐式返回 None
  • 函数可以只有 return,没有值,也会返回 None,用于提前结束函数。
  • 函数可以返回一个或多个值。返回多个值时,实际上是返回一个元组

示例:

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):
    sum = x + y
    product = x * y
    difference = x - y
    return sum, product, difference # 返回一个元组 (sum, product, difference)

result = calculate(10, 5)
print(result) # 输出:(15, 50, 5)
# 可以使用解包
s, p, d = calculate(10, 5)

五、变量作用域 (Scope)

变量的作用域决定了其可访问性。

  • 局部变量 (Local Variable): 在函数内部定义的变量。只能在定义它的函数内部访问。形参也是局部变量。
  • 全局变量 (Global Variable): 在函数外部定义的变量。可以在整个程序中访问。

规则:

  1. 函数内可以读取全局变量的值。
  2. 如果函数内部尝试修改全局变量,Python 会默认在函数内部创建一个新的同名局部变量。要修改全局变量,必须使用 global 关键字声明。

示例:

x = 10  # 全局变量

def my_func():
    global x  # 声明 x 是全局变量,接下来要修改它
    x = 20    # 修改全局变量 x
    y = 5     # 局部变量 y
    print(f"Inside function: x = {x}, y = {y}") # x=20, y=5

my_func()
print(f"Outside function: x = {x}") # x=20
# print(y) # 这里会报错:NameError: name 'y' is not defined

最佳实践: 尽量避免使用全局变量,优先通过参数和返回值在函数间传递数据,这会使代码更清晰、更易于调试。


六、Lambda 函数(匿名函数)

Lambda 函数是一种小巧的、匿名的(没有名字)、内联的函数。

语法:
lambda arguments: expression

  • lambda 是关键字。
  • arguments 是参数列表,与普通函数类似。
  • expression 是一个表达式(不是代码块),其计算结果就是函数的返回值。

特点与用途:

  • 功能简单,通常只包含一个表达式。
  • 无需 return 语句,表达式结果自动返回。
  • 常用于需要函数对象作为参数的高阶函数中,如 sorted()map()filter()reduce()

示例:

# 普通函数
def square(x):
    return x * x

# 等效的 Lambda 函数
square_lambda = lambda x: x * x

print(square(5))        # 输出:25
print(square_lambda(5)) # 输出:25

# 更常见的用法:作为参数传递
numbers = [1, 4, 2, 5, 3]
# 使用 lambda 对列表进行排序,按每个数的平方大小
sorted_numbers = sorted(numbers, key=lambda x: x * x)
print(sorted_numbers) # 输出:[1, 2, 3, 4, 5]

# 使用 map 对列表中每个元素应用 lambda 函数
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # 输出:[2, 8, 4, 10, 6]

总结

特性

说明

示例

定义

使用 def 关键字

def my_func():

参数

位置、关键字、默认、可变(*args**kwargs)

def func(a, b=1, *c, **d):

返回值

使用 return,可返回多个值(元组)

return a, b, c

作用域

局部变量 vs 全局变量 (global)

global var_name

Lambda

匿名函数,简洁的内联函数

lambda x: x+1

掌握函数是成为优秀 Python 程序员的关键一步。从简单的代码封装到灵活的参数处理,再到函数式编程的基石 Lambda,这些概念共同构成了 Python 强大功能的核心。