Python之函数

发布于:2025-03-30 ⋅ 阅读:(20) ⋅ 点赞:(0)

        前言

一、Python 函数基础

1. 函数定义

2. 代码示例

二、函数参数类型

1. 位置参数

2. 默认参数

3. 可变参数 (*args)

4. 关键字参数 (**kwargs)

三、实际应用案例

案例1:数据处理函数

案例2:计算器程序

前言

这部分内容之前写过,但感觉不是特别好,不方便以后翻阅,所以重新整理。有问题欢迎随时指正。

一、Python 函数基础

1. 函数定义

def function_name(parameters):
    """函数文档字符串(可选)"""
    # 函数体
    return value  # 可选返回值

2. 代码示例

# 基本加法函数
def add_numbers(a, b):
    """返回两个数字的和"""
    result = a + b
    return result

# 调用函数
sum_result = add_numbers(3, 5)
print(sum_result)  # 输出 8

二、函数参数类型

1. 位置参数

def greet(name, greeting):
    print(f"{greeting}, {name}!")

greet("Alice", "Hello")  # 输出 "Hello, Alice!"

2. 默认参数

def power(base, exponent=2):
    return base ** exponent

print(power(3))     # 输出 9 (3^2)
print(power(2, 4))  # 输出 16 (2^4)

3. 可变参数 (*args)

def average(*numbers):
    return sum(numbers) / len(numbers)

print(average(1, 2, 3))    # 输出 2.0
print(average(4, 5, 6, 7)) # 输出 5.5

4. 关键字参数 (**kwargs)

def person_info(**details):
    for key, value in details.items():
        print(f"{key}: {value}")

person_info(name="Bob", age=30, city="New York")
# 输出:
# name: Bob
# age: 30
# city: New York

三、实际应用案例

案例1:数据处理函数

import csv
import json
from datetime import datetime
from typing import List, Dict, Union

def process_sales_data(file_path: str, 
                      start_date: str = None, 
                      end_date: str = None) -> List[Dict[str, Union[str, float]]]:
    """
    完整销售数据处理函数
    
    功能:
    1. 读取CSV文件
    2. 数据清洗和验证
    3. 数据类型转换
    4. 日期范围过滤
    5. 计算附加字段
    6. 处理异常数据
    
    参数:
    file_path (str): 数据文件路径
    start_date (str): 过滤开始日期 (YYYY-MM-DD)
    end_date (str): 过滤结束日期 (YYYY-MM-DD)
    
    返回:
    List[Dict]: 处理后的数据列表,每个元素为包含处理结果的字典
    """
    processed_data = []
    
    try:
        # 1. 读取CSV文件
        with open(file_path, 'r', encoding='utf-8') as f:
            reader = csv.DictReader(f)
            raw_data = [row for row in reader]
            
            if not raw_data:
                raise ValueError("文件为空或格式不正确")

            # 2. 数据清洗和处理
            for idx, row in enumerate(raw_data, 1):
                try:
                    # 数据验证
                    required_fields = ['order_id', 'order_date', 'product', 'quantity', 'unit_price']
                    for field in required_fields:
                        if field not in row or not row[field].strip():
                            raise ValueError(f"记录 {idx} 缺少必要字段: {field}")

                    # 类型转换
                    order_date = datetime.strptime(row['order_date'], '%Y-%m-%d')
                    quantity = int(row['quantity'])
                    unit_price = float(row['unit_price'])
                    
                    # 计算总金额
                    total = quantity * unit_price
                    
                    # 日期过滤
                    if start_date and end_date:
                        start = datetime.strptime(start_date, '%Y-%m-%d')
                        end = datetime.strptime(end_date, '%Y-%m-%d')
                        if not (start <= order_date <= end):
                            continue

                    # 构建处理后的记录
                    processed_record = {
                        'order_id': row['order_id'],
                        'order_date': order_date.strftime('%Y-%m-%d'),
                        'product': row['product'].strip().title(),
                        'quantity': quantity,
                        'unit_price': unit_price,
                        'total_amount': round(total, 2),
                        'discount': calculate_discount(quantity, total)
                    }

                    processed_data.append(processed_record)

                except (ValueError, TypeError) as e:
                    print(f"记录 {idx} 处理失败: {str(e)}")
                    continue

        # 3. 数据后处理
        if processed_data:
            # 按日期排序
            processed_data.sort(key=lambda x: x['order_date'])

            # 保存处理后的数据
            save_processed_data(processed_data)
            
        return processed_data

    except FileNotFoundError:
        print(f"错误:文件 {file_path} 未找到")
        return []
    except Exception as e:
        print(f"处理过程中发生意外错误: {str(e)}")
        return []

def calculate_discount(quantity: int, total: float) -> float:
    """计算折扣逻辑"""
    if quantity > 100:
        return round(total * 0.15, 2)
    elif quantity > 50:
        return round(total * 0.1, 2)
    return 0.0

def save_processed_data(data: List[Dict], 
                       format: str = 'csv',
                       output_file: str = 'processed_sales.csv'):
    """保存处理后的数据"""
    try:
        if format == 'csv':
            with open(output_file, 'w', newline='', encoding='utf-8') as f:
                writer = csv.DictWriter(f, fieldnames=data[0].keys())
                writer.writeheader()
                writer.writerows(data)
        elif format == 'json':
            with open(output_file.replace('.csv', '.json'), 'w') as f:
                json.dump(data, f, indent=2)
        print(f"数据已保存至 {output_file}")
    except Exception as e:
        print(f"保存数据失败: {str(e)}")

# 生成模拟测试数据
def generate_sample_data(file_name: str = 'sales_data.csv'):
    sample_data = [
        ['order_id', 'order_date', 'product', 'quantity', 'unit_price'],
        ['1001', '2023-01-05', ' Laptop ', '2', '899.99'],
        ['1002', '2023-02-12', ' Mouse ', '50', '19.99'],
        ['1003', '2023-03-18', ' Keyboard ', '120', '49.99'],
        ['1004', '2023-03-20', ' Monitor ', '1', '299.99'],
        ['1005', 'invalid_date', ' Headphones ', '5', '149.99'],  # 无效日期
        ['1006', '2023-04-01', ' Cable ', 'thirty', '9.99'],      # 无效数量
        ['1007', '2023-05-15', '  ', '10', '29.99']             # 缺失产品名称
    ]

    with open(file_name, 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerows(sample_data)

# 使用示例
if __name__ == "__main__":
    # 生成测试数据
    generate_sample_data()
    
    # 处理数据(带日期过滤)
    processed = process_sales_data(
        file_path='sales_data.csv',
        start_date='2023-02-01',
        end_date='2023-03-31'
    )
    
    # 显示处理结果
    print("\n成功处理的记录:")
    for record in processed:
        print(f"{record['order_date']} | {record['product']:10} | "
              f"数量: {record['quantity']:3} | 总金额: ${record['total_amount']:7.2f} "
              f"(折扣: ${record['discount']:.2f})")
    
    # 保存JSON格式
    save_processed_data(processed, format='json', output_file='sales_processed.json')

案例2:计算器程序

def calculator():
    """简单命令行计算器"""
    while True:
        print("\n操作选项:")
        print("1. 加法  2. 减法  3. 乘法  4. 除法  5. 退出")
        choice = input("请选择操作 (1-5): ")

        if choice == '5':
            break

        num1 = float(input("输入第一个数字: "))
        num2 = float(input("输入第二个数字: "))

        if choice == '1':
            print(f"结果: {num1 + num2}")
        elif choice == '2':
            print(f"结果: {num1 - num2}")
        elif choice == '3':
            print(f"结果: {num1 * num2}")
        elif choice == '4':
            if num2 != 0:
                print(f"结果: {num1 / num2}")
            else:
                print("错误:除数不能为零!")
        else:
            print("无效的输入!")

# 启动计算器
calculator()