Python销售数据存储分析程序analyze_data函数变量未定义问题修复
销售数据程序修复方案
现有问题梳理
- 变量作用域错误:
request_data中定义的software_accumulator等均为函数局部变量,函数执行结束后外部无法直接访问,analyze_data中直接调用这些变量必然报错 - 文件写入逻辑错误:换行符误用为
/n(正确应为\n),且float类型的销售额未转字符串就直接拼接写入,会触发类型报错 - 逻辑流程错误:
analyze_data中重复调用request_data会导致反复要求用户输入数据,且完全没有读取已有文件内容的逻辑 - 提示信息位置错误:记录数打印放在循环内,每次添加国家都会重复打印,不符合要求的「输入完成后显示总记录数」
修复后完整代码
# 请求用户输入国家名称,验证长度不少于2个字符且为纯字母 def request_countryname(): min_length = 2 while True: country = input("请输入国家名称:") if len(country) < min_length or not country.isalpha(): print("国家名称长度不能少于2个字符,且只能包含字母") else: return country # 请求用户输入对应国家对应产品的销售额,验证为非负数值 def request_sales(product, country_name): while True: sales_input = input(f"请输入{country_name}地区{product}的总销售额:$ ") try: sales = float(sales_input) except ValueError: print("销售额必须为数字") continue if sales < 0: print("销售额不能为负数") continue return sales # 循环采集销售数据,写入文件并返回总记录数 def request_data(file_path): count = 0 with open(file_path, "w", encoding="utf-8") as f: again = "y" while again.lower() == "y": country_name = request_countryname() software_sales = request_sales("软件", country_name) hardware_sales = request_sales("硬件", country_name) accessories_sales = request_sales("配件", country_name) # 写入文件,注意换行符和类型转换 f.write(f"{country_name}\n") f.write(f"{software_sales}\n") f.write(f"{hardware_sales}\n") f.write(f"{accessories_sales}\n") count += 1 again = input("是否要添加另一个国家的数据?(输入y/Y确认):") print(f"共{count}条记录已成功写入文件") return count # 读取文件分析销售数据 def analyze_data(file_path): software_total = 0 hardware_total = 0 accessories_total = 0 country_count = 0 with open(file_path, "r", encoding="utf-8") as f: lines = [line.strip() for line in f if line.strip()] # 每4行对应一个国家的完整数据:国家名、软件销售额、硬件销售额、配件销售额 for i in range(0, len(lines), 4): software_total += float(lines[i+1]) hardware_total += float(lines[i+2]) accessories_total += float(lines[i+3]) country_count += 1 # 计算平均值 avg_software = software_total / country_count avg_hardware = hardware_total / country_count avg_accessories = accessories_total / country_count total_sales = software_total + hardware_total + accessories_total # 输出结果 print("----------------------------") print(f"单国平均软件销售额:$ {avg_software:,.2f}") print(f"单国平均硬件销售额:$ {avg_hardware:,.2f}") print(f"单国平均配件销售额:$ {avg_accessories:,.2f}") print() print(f"软件总销售额:$ {software_total:,.2f}") print(f"硬件总销售额:$ {hardware_total:,.2f}") print(f"配件总销售额:$ {accessories_total:,.2f}") print() print(f"总销售额:$ {total_sales:,.2f}") def main(): file_path = "sales_data.txt" request_data(file_path) analyze_data(file_path) if __name__ == "__main__": main()
修复说明
- 用
with语句管理文件句柄,不需要手动调用close(),避免文件泄露 analyze_data完全基于文件内容计算,不需要依赖其他函数的局部变量,逻辑独立- 统一了输入输出的中文提示,符合使用场景
- 所有数值转换、换行符问题均已修复,可直接运行
内容的提问来源于stack exchange,提问作者Monique
相关产品推荐
相关产品推荐

