基于Python分析客户:计算指定客户总支出与指定日期总支出
问题分析与代码修正
原代码存在的核心问题
- 语法错误:
print(row)r]属于笔误,多余的r]会直接导致代码运行报错 - 缺失核心统计逻辑:未初始化用于统计支出的字典(
dates及客户支出相关变量均未定义),读取文件后未解析每行数据,完全没实现统计功能 - 返回值不匹配:函数注解声明返回
(float, float),但代码返回字符串,违背类型约定 - 异常处理不规范:
except捕获所有异常,应该针对性处理文件读取相关异常(如FileNotFoundError) - 逻辑结构错误:与
for循环绑定的else块位置不合理,无法实现预期的判断逻辑
修正后的代码(假设文件为CSV格式,每行内容为客户名,日期,支出金额)
def analysis(file: str, customer: str, date: str) -> tuple[float, float]: customer_total = 0.0 date_total = 0.0 try: with open(file, 'r') as filehand: # 跳过表头(如果文件无表头可删除此行) next(filehand) for row in filehand: row = row.strip() if not row: continue # 分割每行数据,按约定格式解析 parts = row.split(',') if len(parts) != 3: continue # 跳过格式错误的行 try: cust, dt, amount = parts amount = float(amount) except ValueError: continue # 跳过金额无法转换的行 # 累加指定客户的支出 if cust == customer: customer_total += amount # 累加指定日期的支出 if dt == date: date_total += amount except FileNotFoundError: print("File not found") return 0.0, 0.0 except Exception as e: print(f"Unexpected error: {e}") return 0.0, 0.0 return customer_total, date_total
代码说明
- 初始化
customer_total和date_total为0.0,确保最终返回符合(float, float)的类型约定 - 针对性捕获
FileNotFoundError,同时保留通用异常处理避免程序崩溃 - 逐行解析文件内容,跳过空行和格式错误的行,避免无效数据干扰统计
- 分别累加指定客户和指定日期的支出金额
- 无论是否找到对应客户或日期,均返回浮点数值(未找到时为0.0),符合函数的类型注解要求
内容的提问来源于stack exchange,提问作者soccergirlylegends9
相关产品推荐
相关产品推荐

