如何永久存储用户输入以累加至总变量?预算程序开发技术问询
解决你的预算程序持久化累加问题
首先直接回答你的疑问:不需要把pay_this_week转为列表追加到total。total是一个表示总收入的数值,应该做的是将新输入的周收入和历史总收入做数值累加;如果需要记录每一次的收入明细,列表才是适合的载体,但这和总收入的累加逻辑是分开的。你的核心问题是现有代码没有实现数据持久化——每次运行程序时total都会被重置为0,导致之前的累加记录全部丢失。
现有代码的问题分析
你当前的代码里,total = int()会在每次调用money_earnt()时把总收入重置为0,所以不管你输入多少次,每次运行程序都只能计算单次输入的金额,无法保留历史数据。要实现永久存储,我们需要把数据写到文件(或数据库)中,下次运行时从文件读取历史值再进行累加。
解决方案1:仅持久化总收入
这个方案适合只需要记录总收入的场景,用一个简单的文本文件存储当前的总收入:
def money_earnt(): # 定义存储总收入的文件路径 total_file = "total_earned.txt" # 尝试读取历史总收入,文件不存在则初始化为0 try: with open(total_file, "r") as f: total = int(f.read().strip()) except (FileNotFoundError, ValueError): # 文件不存在或内容不是有效数字时,初始化为0 total = 0 # 获取用户输入的本周收入 while True: try: pay_this_week = int(input("How much money did you earn this week? ")) break except ValueError: print("Oops! That was no valid number. Try again...") # 累加总收入 total += pay_this_week # 将新的总收入写回文件 with open(total_file, "w") as f: f.write(str(total)) # 输出提示信息 pay_this_week_message = "You've earnt £{0} this week!".format(pay_this_week) total_message = "You have earned £{0} in total!".format(total) print(pay_this_week_message) print(total_message) money_earnt()
解决方案2:持久化每次收入明细+总收入
如果需要记录每一周的收入详情(比如后续可以查看每周收入情况),可以用JSON格式存储一个包含明细列表和总收入的字典:
import json def money_earnt(): data_file = "budget_data.json" # 读取历史数据 try: with open(data_file, "r") as f: budget_data = json.load(f) # 确保数据结构正确 total = budget_data.get("total", 0) weekly_earnings = budget_data.get("weekly_earnings", []) except (FileNotFoundError, json.JSONDecodeError): # 初始数据 total = 0 weekly_earnings = [] # 获取本周收入 while True: try: pay_this_week = int(input("How much money did you earn this week? ")) break except ValueError: print("Oops! That was no valid number. Try again...") # 更新数据 weekly_earnings.append(pay_this_week) total += pay_this_week # 保存更新后的数据 with open(data_file, "w") as f: json.dump({ "total": total, "weekly_earnings": weekly_earnings }, f, indent=4) # 输出信息 print(f"You've earnt £{pay_this_week} this week!") print(f"You have earned £{total} in total!") print(f"All weekly earnings: {['£' + str(earn) for earn in weekly_earnings]}") money_earnt()
关键说明
- 两种方案都通过文件实现了数据持久化,程序关闭再重启后,之前的累加记录依然存在。
- 方案1更轻量,适合只关注总收入的需求;方案2保留了每一次的收入记录,方便后续扩展功能(比如统计周平均收入)。
- 处理了文件不存在、文件内容无效等异常情况,保证程序的健壮性。
内容的提问来源于stack exchange,提问作者winterwolf
相关产品推荐
相关产品推荐

