七、python函数
目录
1. 函数的定义与调用
1.1 定义函数
1.2 调用函数
2. 函数的参数
2.1 位置参数
2.2 默认参数
2.3 关键字参数
2.4 可变参数
3. 函数的返回值
3.1 返回单个值
3.2 返回多个值
3.3 不返回值
4. 变量的作用域
4.1 局部变量
4.2 全局变量
5. 函数的高级特性
5.1 闭包
5.2 装饰器
输出:
5.3 lambda 函数
6. 函数的实际应用
6.1 作为参数传递
6.2 返回函数
7. 总结
1. 函数的定义与调用
1.1 定义函数
使用 def
关键字定义函数,后跟函数名、参数列表和函数体。
def function_name(parameters):
"""函数文档字符串"""
# 函数体
return value # 可选的返回值
1.2 调用函数
定义函数后,可以通过函数名和参数来调用它。
def greet(name):
"""打印问候语"""
print(f"Hello, {name}!")
greet("Alice") # 输出:Hello, Alice!
2. 函数的参数
2.1 位置参数
按顺序传递的参数,位置必须对应。
def add(a, b):
return a + b
print(add(3, 5)) # 输出:8
2.2 默认参数
在定义函数时为参数设置默认值。
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # 输出:Hello, Alice!
greet("Bob", "Hi") # 输出:Hi, Bob!
2.3 关键字参数
调用函数时使用键值对的形式传递参数,顺序可以不同。
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet(animal_type="dog", pet_name="Buddy")
describe_pet(pet_name="Buddy", animal_type="dog")
2.4 可变参数
使用 *args
接收任意数量的位置参数,使用 **kwargs
接收任意数量的关键字参数。
def sum_numbers(*args):
return sum(args)
print(sum_numbers(1, 2, 3)) # 输出:6
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25)
3. 函数的返回值
3.1 返回单个值
使用 return
语句返回单个值。
def multiply(a, b):
return a * b
result = multiply(4, 5)
print(result) # 输出:20
3.2 返回多个值
可以通过元组返回多个值。
def divide(a, b):
return a // b, a % b
quotient, remainder = divide(10, 3)
print(f"商:{quotient},余数:{remainder}") # 输出:商:3,余数:1
3.3 不返回值
如果函数没有 return
语句,它会返回 None
。
def say_hello():
print("Hello!")
result = say_hello()
print(result) # 输出:None
4. 变量的作用域
4.1 局部变量
在函数内部定义的变量,作用域仅限于函数内部。
def my_function():
x = 10 # 局部变量
print(x)
my_function()
# print(x) # 错误:NameError: name 'x' is not defined
4.2 全局变量
在函数外部定义的变量,可以在函数内部访问,但修改需要使用 global
关键字。
y = 20 # 全局变量
def modify_global():
global y
y = 30
modify_global()
print(y) # 输出:30
5. 函数的高级特性
5.1 闭包
闭包是能够访问其定义时作用域中变量的函数。
def outer_function():
message = "Hello" # 外部函数中的变量
def inner_function():
print(message) # 内部函数访问外部变量
return inner_function
my_func = outer_function()
my_func() # 输出:Hello
5.2 装饰器
装饰器是用于修改其他函数功能的高阶函数。
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
输出:
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
5.3 lambda 函数
lambda 函数是匿名函数,适用于简单的操作。
# 使用 lambda 定义匿名函数
add = lambda a, b: a + b
print(add(3, 5)) # 输出:8
# 在列表排序中使用 lambda
students = [("Alice", 25), ("Bob", 20), ("Charlie", 30)]
students.sort(key=lambda student: student[1])
print(students) # 输出:[('Bob', 20), ('Alice', 25), ('Charlie', 30)]
6. 函数的实际应用
6.1 作为参数传递
函数可以作为参数传递给其他函数。
def apply_function(func, x):
return func(x)
def square(n):
return n ** 2
result = apply_function(square, 5)
print(result) # 输出:25
6.2 返回函数
函数可以返回另一个函数。
def outer_function(a):
def inner_function(b):
return a + b
return inner_function
add_five = outer_function(5)
print(add_five(3)) # 输出:8
7. 总结
函数是 Python 中实现代码复用和模块化的基石。通过掌握函数的定义、参数处理、返回值、作用域以及高级特性(如闭包和装饰器),你可以编写出高效、可维护的代码。