PYTHON训练营DAY26

发布于:2025-05-15 ⋅ 阅读:(6) ⋅ 点赞:(0)

一、函数

(一)不带参数的函数

# 定义一个简单的问候函数
def greet():
    """打印一句问候语。"""
    message = "大家好!欢迎学习Python函数定义!"
    print(message)

greet()

(二)带参数的函数

# 定义一个带一个参数的问候函数
def greet_person(name):
    """根据给定的名字打印问候语。

    Args:
        name (str): 要问候的人的名字。
    """
    message = f"你好, {name}! 很高兴认识你。"
    print(message)

greet_person("张三")  # 输出: 你好, 张三! 很高兴认识你。
# 定义一个带多个参数的函数 (例如,在机器学习中计算两个特征的和)
def add_features(feature1, feature2):
    """计算两个数值特征的和。

    Args:
        feature1 (float or int): 第一个特征值。
        feature2 (float or int): 第二个特征值。
    """
    total = feature1 + feature2
    print(f"{feature1} + {feature2} = {total}")

add_features(10, 25)       # 输出: 10 + 25 = 35
# add_features(5) 
# 这会报错,因为少了一个参数 TypeError

(三)带返回值的函数

# 定义一个计算和并返回结果的函数
def calculate_sum(a, b):
    """计算两个数的和并返回结果。

    Args:
        a (float or int): 第一个数。
        b (float or int): 第二个数。

    Returns:
        float or int: 两个数的和。
    """
    result = a + b
    return result
    print("hhh")

calculate_sum(2, 3)
# 函数可以返回多种类型的数据,包括列表、字典等
# 例如,在数据预处理中,一个函数可能返回处理后的特征列表
def preprocess_data(raw_data_points):
    """模拟数据预处理,例如将所有数据点乘以2。

    Args:
        raw_data_points (list): 原始数据点列表。

    Returns:
        list: 处理后的数据点列表。
    """
    processed = []
    for point in raw_data_points:
        processed.append(point * 2) # 假设预处理是乘以2
    return processed

data = [1, 2, 3, 4, 5]
processed_data = preprocess_data(data)

print(f"原始数据: {data}")
print(f"预处理后数据: {processed_data}") # 输出: [2, 4, 6, 8, 10]

二、变量作用域

print("\n--- 变量作用域示例 ---")
global_var = "我是一个全局变量"

def scope_test():
    local_var = "我是一个局部变量"
    print(f"在函数内部,可以看到局部变量: '{local_var}'")
    print(f"在函数内部,也可以看到全局变量: '{global_var}'")
    # global_var = "尝试在函数内修改全局变量" # 如果没有 global 声明,这会创建一个新的局部变量 global_var
    # print(f"在函数内部,修改后的 '全局' 变量: '{global_var}'")

scope_test()

print(f"\n在函数外部,可以看到全局变量: '{global_var}'")

三、应用

(一)计算圆的面积

  • 任务: 编写一个名为 calculate_circle_area 的函数,该函数接收圆的半径 radius 作为参数,并返回圆的面积。圆的面积 = π * radius² (可以使用 math.pi 作为 π 的值)
  • 要求:函数接收一个位置参数 radius。计算半径为5、0、-1时候的面积
  • 注意点:可以采取try-except 使函数变得更加稳健,如果传入的半径为负数,函数应该返回 0 (或者可以考虑引发一个ValueError,但为了简单起见,先返回0)。
import math

def calculate_circle_area(radius):
    try:
        if radius < 0:
            return 0
        return math.pi * (radius ** 2)
    except TypeError:
        return 0

# 测试示例
print(calculate_circle_area(5))  # 输出约78.53981633974483
print(calculate_circle_area(0))   # 输出0.0
print(calculate_circle_area(-1))  # 输出0
print(calculate_circle_area("a")) # 输出0(处理非数字输入)    

(二)计算矩形的面积

  • 任务: 编写一个名为 calculate_rectangle_area 的函数,该函数接收矩形的长度 length 和宽度 width 作为参数,并返回矩形的面积。
  • 公式: 矩形面积 = length * width
  • 要求:函数接收两个位置参数 length 和 width。
    • 函数返回计算得到的面积。
    • 如果长度或宽度为负数,函数应该返回 0
def calculate_rectangle_area(length, width):
    if length < 0 or width < 0:
        return 0
    return length * width

# 测试示例
print(calculate_rectangle_area(5, 3))   # 输出15
print(calculate_rectangle_area(-2, 4))  # 输出0
print(calculate_rectangle_area(5, -3))  # 输出0
print(calculate_rectangle_area(-2, -4)) # 输出0    

(三)计算任意数量数字的平均值

  • 任务: 编写一个名为 calculate_average 的函数,该函数可以接收任意数量的数字作为参数(引入可变位置参数 (*args)),并返回它们的平均值。
  • 要求:使用 *args 来接收所有传入的数字。
    • 如果没有任何数字传入,函数应该返回 0。
    • 函数返回计算得到的平均值。
def calculate_average(*args):
    if not args:
        return 0
    return sum(args) / len(args)

# 测试示例
print(calculate_average(1, 2, 3, 4))  # 输出2.5
print(calculate_average(10, 20))      # 输出15.0
print(calculate_average())            # 输出0
print(calculate_average(-5, 5, 0))    # 输出0.0    

(四)打印用户信息

  • 任务: 编写一个名为 print_user_info 的函数,该函数接收一个必需的参数 user_id,以及任意数量的额外用户信息(作为关键字参数)。
  • 要求:
    • user_id 是一个必需的位置参数。
    • 使用 **kwargs 来接收额外的用户信息。
    • 函数打印出用户ID,然后逐行打印所有提供的额外信息(键和值)。
    • 函数不需要返回值
def print_user_info(user_id, **kwargs):
    print(f"用户ID: {user_id}")
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# 测试示例
print_user_info(12345, name="张三", age=30, city="北京")
print_user_info(67890, email="test@example.com", subscribed=True)
print_user_info(10101)  # 仅提供必需参数    

(五)格式化几何图形描述

  • 任务: 编写一个名为 describe_shape 的函数,该函数接收图形的名称 shape_name (必需),一个可选的 color (默认 “black”),以及任意数量的描述该图形尺寸的关键字参数 (例如 radius=5 对于圆,length=10, width=4 对于矩形)。
  • 要求:shape_name 是必需的位置参数。
    • color 是一个可选参数,默认值为 “black”
    • 使用 **kwargs 收集描述尺寸的参数。
    • 函数返回一个描述字符串,格式如下:
    • “A [color] [shape_name] with dimensions: [dim1_name]=[dim1_value], [dim2_name]=[dim2_value], …”如果 **kwargs 为空,则尺寸部分为 “with no specific dimensions.”
def describe_shape(shape_name, color="black", **kwargs):
    dimensions = ', '.join(f"{k}={v}" for k, v in kwargs.items())
    dim_text = f"with dimensions: {dimensions}" if dimensions else "with no specific dimensions."
    return f"A {color} {shape_name} {dim_text}"

# 测试示例
print(describe_shape("circle", "red", radius=5))
print(describe_shape("rectangle", length=10, width=4))
print(describe_shape("square", "blue", side=5))
print(describe_shape("line", "green"))    

@浙大疏锦行