优化Python财务跟踪程序

2024-06-01 06:29:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个跟踪退休财务状况的基本计划。到目前为止,我得到的是一个条目的输入并存储它。下次我运行它时,前面的值会被删除。理想情况下,我想要的是一个程序,无限期地附加到一个列表,如果我打开它从现在起两个星期,我希望能够看到dict格式的当前数据,并添加到它。我设想运行这个脚本,输入帐户名和余额,然后关闭它,稍后再执行

几个问题:

  1. 我如何做到这一点?我想我需要一些循环的概念才能到达那里
  2. 有没有一种更优雅的方法来输入帐户名和余额,而不是像我下面那样在参数中硬编码?我尝试了input(),但它只针对帐户名运行,不针对余额(同样,可能与循环相关)
  3. 我想添加一些错误检查,因此如果用户没有输入有效的帐户,比如(HSA、401k或Roth),系统会提示他们重新输入。输入/检查应在哪里进行

谢谢

from datetime import datetime

Account = {
    "name": [],
    "month": [],
    "day": [],
    "year": [],
    "balance": []
}

finance = [Account]

def finance_data(name, month, day, year, balance):

    Account['name'].append(name)
    Account['month'].append(month)
    Account['day'].append(day)
    Account['year'].append(year)
    Account['balance'].append(balance)
    print(finance)


finance_data('HSA',
        datetime.now().month,
        datetime.now().day,
        datetime.now().year, 
        500)

Tags: namedatadatetimeaccountyearnow余额balance
1条回答
网友
1楼 · 发布于 2024-06-01 06:29:16

当您运行脚本并将值放入代码中定义的变量中时,这些值只会持续程序运行的时间。每次运行脚本时,它都会从代码中定义的初始状态重新开始,因此不会保存上次运行脚本时的状态

您需要的是持续时间超过脚本运行时的持久数据。通常,我们通过创建一个数据库来实现这一点,使用脚本将新数据写入数据库,然后,当脚本接下来运行时,从数据库中读取旧值以记住过去发生的事情。然而,由于您的用例较小,它可能不需要完整的数据库系统。相反,我建议将数据写入文本文件,然后从文本文件中读取以获取旧数据。你可以这样做:

# read about file io in python here: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
dataStore = open("dataFile.txt", "r+") # r+ is the read and write mode

def loadDataToAccount(dataStore):


    Account = {
        "name": [],
        "month": [],
        "day": [],
        "year": [],
        "balance": []
    }

    for line in dataStore.read().splitlines():
        (name, month, day, year, balance) = line.split("|")
        Account['name'].append(name)
        Account['month'].append(month)
        Account['day'].append(day)
        Account['year'].append(year)
        Account['balance'].append(balance)
    return Account

Account = loadDataToAccount(dataStore)

在这里,我假设我们组织文本文件,使每一行都是一个条目,条目以“|”分隔,例如: 鲍勃| 12 | 30 | 1994 | 500 罗布| 11 | 29 | 1993 | 499

因此,我们可以将文本解析到Account字典中。现在,让我们看看如何将数据输入到文本文件中:

def addData(Account, dataStore):
    name = raw_input("Enter the account name: ")
    balance = raw_input("Enter the account balance: ")
    # put name and balance validation here!

    month = datetime.now().month
    day = datetime.now().day
    year = datetime.now().year

    # add to Account
    Account['name'].append(name)
    Account['month'].append(month)
    Account['day'].append(day)
    Account['year'].append(year)
    Account['balance'].append(balance)

    # also add to our dataStore
    dataStore.write(name + "|" + month + "|" + day + "|" + year + "|" + balance + "\n")

addData(Account, dataStore)

注意这里我是如何用我定义的预期格式将它写入数据存储的。如果不将其写入文本文件,它将不会保存数据并在下次运行时可用

另外,我还使用输入来获取名称和平衡,这样它更具动态性。在收集输入之后,您可以放置if语句以确保它是一个有效的名称,然后使用某种while循环结构来不断请求名称,直到它们输入一个有效的名称为止

您可能希望提取将值添加到Account的代码,并将其放入helper函数中,因为我们使用同一代码两次

祝你好运

相关问题 更多 >