Skip to content

函数

函数的分类

内置函数模块提供的函数自定义函数
如:print()、len()、range() 等如:math 模块提供的函数由用户自己定义的函数

函数的定义

python
def function_name(parameters):
    """
    函数的文档字符串(可选)
    """
    # 函数体
    # 可以包含多个语句
    # 最后可以有一个可选的返回语句(return)
    # 用于返回函数的结果
    # 如果没有返回语句,函数将返回 None
    return result

函数的案例

案例1:简单的函数

python
def say_hello():
    print("Hello, world!")
# 调用函数
say_hello()  # 输出:Hello, world!

案例2:带参数的函数

python
def greet(name):
    print("Hello, " + name + "!")
# 调用函数
greet("Alice")  # 输出:Hello, Alice!

案例3:带返回值的函数

python
def add_numbers(a, b):
    return a + b
# 调用函数
result = add_numbers(3, 5)
print(result)  # 输出:8

案例4:带默认参数的函数

python
def power(base, exponent=2):
    return base ** exponent
# 调用函数
result = power(3)
print(result)  # 输出:9
result = power(3, 4)
print(result)  # 输出:81

案例5:关键字参数

python
def greet(name, age, gender, height):
    print("Hello, " + name + "! You are " + str(age) + " years old. " + gender + ". " + "Your height is " + str(height) + " meters.")
# 调用函数 使用关键字参数时,位置参数必须在关键字参数之前
greet("Bob", gender="male", age=25, height=1.75)  # 输出:Hello, Bob! You are 25 years old. Male. Your height is 1.75 meters.

案例6:限制传参的方式

python
def greet(name, /, age, *, gender, height):
    print("Hello, " + name + "! You are " + str(age) + " years old. " + gender + ". " + "Your height is " + str(height) + " meters.")
    # / 前面只能用位置参数
    # * 后面只能用关键字参数
    # 调用函数
    greet("Bob", 25, gender="male", height=1.75)  # 输出:Hello, Bob! You are 25 years old. Male. Your height is 1.75 meters.
    greet("Bob", gender="male", age=25, height=1.75)  # 输出:Hello, Bob! You are 25 years old. Male. Your height is 1.75 meters.
    # greet("Bob", 25, "male", 1.75)  # 错误:gender 和 height 必须用关键字参数传递

案例7:可变位置参数

python
def add_numbers(*args):
    result = 0
    for num in args:
        result += num
    return result
# 调用函数
result = add_numbers(1, 2, 3, 4, 5)
print(result)  # 输出:15

案例8:可变关键字参数

python
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(key + ": " + str(value))
# 调用函数
print_info(name="Alice", age=25, gender="female")  # 输出:name: Alice, age: 25, gender: female

案例9:组合参数

python
def print_info(name, age, *args, **kwargs):
    print("Name:", name)
    print("Age:", age)
    print("Other args:", args)
    print("Other kwargs:", kwargs)
# 调用函数
print_info("Alice", 25, "female", height=1.75, weight=65)
# 输出:
# Name: Alice
# Age: 25
# Other args: ('female',)
# Other kwargs: {'height': 1.75, 'weight': 65}

案例10:参数的解包

python
def print_info(name, age, gender, height):
    print("Name:", name)
    print("Age:", age)
    print("Gender:", gender)
    print("Height:", height)
# 调用函数
print_info(*["Alice", 25, "female", 1.75])  # 输出:Name: Alice, Age: 25, Gender: female, Height: 1.75

案例11:特殊字面量 None

python
def print_info(name, age, gender=None, height=None):
    print("Name:", name)
    print("Age:", age)
    if gender is not None:
        print("Gender:", gender)
    if height is not None:
        print("Height:", height)
# 调用函数
print_info("Alice", 25)  # 输出:Name: Alice, Age: 25
print_info("Bob", 30, "male", 1.80)  # 输出:Name: Bob, Age: 30, Gender: male, Height: 1.8

案例12:作用域

提示

nonlocal 关键字用于在内部函数中修改外部函数的变量。

global 关键字用于在函数中修改全局变量。

python
def outer_function():
    x = 10
    def inner_function():
        nonlocal x
        x = 20
        print("Inner:", x)
    inner_function()
    print("Outer:", x)
# 调用函数
outer_function()
# 输出:
# Inner: 20
# Outer: 20

x = 100
def global_function():
    global x
    x += 1

# 调用函数
global_function()
# 输出:
print("Global:", x)
# Global: 101

案例13:函数嵌套

python
def outer_function():
    def inner_function():
        print("Inner function")
    inner_function()
    print("Outer function")
# 调用函数
outer_function()
# 输出:
# Inner function
# Outer function

案例14:递归函数

python
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
# 调用函数
result = factorial(5)
print(result)  # 输出:120

案例15:匿名函数(lambda)

python
# 定义一个匿名函数,计算两个数的和
add = lambda x, y: x + y
# 调用函数
result = add(3, 5)
print(result)  # 输出:8

案例16:函数的说明文档

python
def add_numbers(a, b):
    """
    计算两个数的和
    :param a: 第一个数
    :param b: 第二个数
    :return: 两个数的和
    """
    return a + b
# 调用函数
result = add_numbers(3, 5)
print(result)  # 输出:8

Released under the MIT License.