Python 个人预算跟踪器



个人预算跟踪器用于管理您的收入和支出。在这里,我们将使用不同的方法在 Python 中创建个人预算跟踪器。

使用字典的简单预算跟踪器

字典是处理值集的最方便的形式,因此,我们的收入和支出将以相同的方式管理。这种方法使我们能够轻松地对我们的财务数据进行分类,并且可以毫不费力地完成诸如输入新数据、计算总计和准备摘要等常规任务。

实施

我们创建两个字典:一个用于收入,一个用于支出。每种类型(如“工资”或“租金”)都是字典中的键,每个对应的金额是值。这使我们能够轻松地对收入和支出进行分类和汇总。

代码

# Simple Budget Tracker Using Dictionaries

class BudgetTracker:
   def __init__(self):
      self.income = {}
      self.expenses = {}

   def add_income(self, amount, category):
      if category in self.income:
         self.income[category] += amount
      else:
         self.income[category] = amount

   def add_expense(self, amount, category):
      if category in self.expenses:
         self.expenses[category] += amount
      else:
         self.expenses[category] = amount

   def get_total_income(self):
      return sum(self.income.values())

   def get_total_expenses(self):
      return sum(self.expenses.values())

   def display_summary(self):
      print('Income Summary:')
      for category, amount in self.income.items():
         print(f'{category}: ${amount}')
      print('Total Income:', self.get_total_income())

      print('Expenses Summary:')
      for category, amount in self.expenses.items():
         print(f'{category}: ${amount}')
      print('Total Expenses:', self.get_total_expenses())

      print('Net Savings:', self.get_total_income() - self.get_total_expenses())

# Example Usage
tracker = BudgetTracker()
tracker.add_income(5000, 'Salary')
tracker.add_income(200, 'Freelance')
tracker.add_expense(1500, 'Rent')
tracker.add_expense(200, 'Groceries')
tracker.add_expense(100, 'Utilities')
tracker.display_summary()

输出

Income Summary:
Salary: $5000
Freelance: $200
Total Income: 5200
Expenses Summary:
Rent: $1500
Groceries: $200
Utilities: $100
Total Expenses: 1800
Net Savings: 3400

总结

脚本打印出所有收入和支出的摘要,以及收入总额、支出总额和净储蓄(收入减去支出)。

使用面向对象概念的预算跟踪器

为了提高预算跟踪器的模块化,我们将 OOP 原则应用到我们的预算跟踪器中。换句话说,它有助于将数据和功能组织成易于理解的形式,并易于重用。这种方法还有助于将来轻松管理、修改和扩展,从而满足现代学习机构的需求。

实施

我们构建了一个 Transaction 类来表示每个收入或支出条目,其中包含金额和类别的属性。BudgetTracker 类包含收入和支出的 Transaction 对象列表。提供了添加收入或支出、计算总计和显示摘要的方法。

代码

# Object-Oriented Budget Tracker

class Transaction:
   def __init__(self, amount, category):
      self.amount = amount
      self.category = category

class BudgetTracker:
   def __init__(self):
      self.income = []
      self.expenses = []

   def add_income(self, amount, category):
      self.income.append(Transaction(amount, category))

   def add_expense(self, amount, category):
      self.expenses.append(Transaction(amount, category))

   def get_total_income(self):
      return sum([transaction.amount for transaction in self.income])

   def get_total_expenses(self):
     return sum([transaction.amount for transaction in self.expenses])

   def display_summary(self):
      print('Income Summary:')
      for transaction in self.income:
         print(f'{transaction.category}: ${transaction.amount}')
      print('Total Income:', self.get_total_income())

      print('Expenses Summary:')
      for transaction in self.expenses:
         print(f'{transaction.category}: ${transaction.amount}')
      print('Total Expenses:', self.get_total_expenses())

      print('Net Savings:', self.get_total_income() - self.get_total_expenses())

# Example Usage
tracker = BudgetTracker()
tracker.add_income(5000, 'Salary')
tracker.add_income(200, 'Freelance')
tracker.add_expense(1500, 'Rent')
tracker.add_expense(200, 'Groceries')
tracker.add_expense(100, 'Utilities')
tracker.display_summary()

输出

Income Summary:
Salary: $5000
Freelance: $200
Total Income: 5200
Expenses Summary:
Rent: $1500
Groceries: $200
Utilities: $100
Total Expenses: 1800
Net Savings: 3400

总结

该脚本打印出每个交易的详细信息和总计,类似于第一种方法。

使用文件处理的高级预算跟踪器

在这种方法中,预算跟踪器的功能将得到扩展,特别是将实现文件处理功能。这使用户能够存储和检索数据,换句话说,使预算跟踪器能够在多个会话中使用。

代码

# Advanced Budget Tracker with File Handling

import json

class BudgetTracker:
   def __init__(self):
      self.income = {}
      self.expenses = {}

   def add_income(self, amount, category):
      if category in self.income:
         self.income[category] += amount
      else:
         self.income[category] = amount

   def add_expense(self, amount, category):
      if category in self.expenses:
         self.expenses[category] += amount
      else:
         self.expenses[category] = amount

   def save_to_file(self, filename):
      data = {
         'income': self.income,
         'expenses': self.expenses
      }
      with open(filename, 'w') as file:
         json.dump(data, file)

   def load_from_file(self, filename):
      with open(filename, 'r') as file:
         data = json.load(file)
         self.income = data['income']
         self.expenses = data['expenses']

   def get_total_income(self):
      return sum(self.income.values())

   def get_total_expenses(self):
      return sum(self.expenses.values())

   def display_summary(self):
      print('Income Summary:')
      for category, amount in self.income.items():
         print(f'{category}: ${amount}')
      print('Total Income:', self.get_total_income())

      print('Expenses Summary:')
      for category, amount in self.expenses.items():
         print(f'{category}: ${amount}')
      print('Total Expenses:', self.get_total_expenses())

      print('Net Savings:', self.get_total_income() - self.get_total_expenses())

# Example Usage
tracker = BudgetTracker()
tracker.add_income(5000, 'Salary')
tracker.add_income(200, 'Freelance')
tracker.add_expense(1500, 'Rent')
tracker.add_expense(200, 'Groceries')
tracker.add_expense(100, 'Utilities')
tracker.save_to_file('budget_data.json')

# Load and display the summary
tracker.load_from_file('budget_data.json')
tracker.display_summary()

输出

Income Summary:
Salary: $5000
Freelance: $200
Total Income: 5200
Expenses Summary:
Rent: $1500
Groceries: $200
Utilities: $100
Total Expenses: 1800
Net Savings: 3400

总结

在此输出中,预算跟踪器可以将数据保存到文件并从文件加载数据。

具有用户输入和文件处理的交互式预算跟踪器

在这种方法中,预算跟踪器将通过交互式用户输入选项来添加收入和支出而得到增强。用户现在可以通过控制台直接提供信息,这极大地提高了应用程序的活力和日常实用性。

解释

user_input() 方法提供了一个菜单驱动的界面,方便添加收入、添加支出、将数据保存到文件、从文件加载数据或退出程序。

用户可以通过控制台输入金额和类别,从而使预算跟踪器更具交互性。

菜单选项:• 添加收入 • 添加支出 • 保存 • 加载 • 退出

代码

import json

class BudgetTracker:
   def __init__(self):
      self.income = {}
      self.expenses = {}

   def add_income(self, amount, category):
      if category in self.income:
         self.income[category] += amount
      else:
         self.income[category] = amount

   def add_expense(self, amount, category):
      if category in self.expenses:
         self.expenses[category] += amount
      else:
         self.expenses[category] = amount

   def save_to_file(self, filename):
      data = {
         'income': self.income,
         'expenses': self.expenses
      }
      with open(filename, 'w') as file:
         json.dump(data, file)

   def load_from_file(self, filename):
      try:
         with open(filename, 'r') as file:
            data = json.load(file)
            self.income = data['income']
            self.expenses = data['expenses']
            print(f"Data loaded successfully from {filename}.")
      except FileNotFoundError:
         print(f"Error: The file '{filename}' does not exist. Please check the filename and try again.")

   def get_total_income(self):
      return sum(self.income.values())

   def get_total_expenses(self):
      return sum(self.expenses.values())

   def display_summary(self):
      print('Income Summary:')
      for category, amount in self.income.items():
         print(f'{category}: ${amount}')
      print('Total Income:', self.get_total_income())

      print('Expenses Summary:')
      for category, amount in self.expenses.items():
         print(f'{category}: ${amount}')
      print('Total Expenses:', self.get_total_expenses())

      print('Net Savings:', self.get_total_income() - self.get_total_expenses())

   def user_input(self):
      print("Welcome to the Budget Tracker!")
      print("You can use the following categories or create your own:")
      print("  - Income: Salary, Freelance, Investments")
      print("  - Expenses: Rent, Groceries, Utilities, Entertainment")

      while True:
         action = input("\nWhat would you like to do? (Add Income/Add Expense/Save/Load/Exit): ").lower()
         if action == 'add income':
            amount = float(input("Enter the amount (e.g., 5000): "))
            category = input("Enter the category (e.g., Salary, Freelance): ")
            self.add_income(amount, category)
            print(f"Added income: ${amount} under '{category}' category.")
         elif action == 'add expense':
            amount = float(input("Enter the amount (e.g., 1500): "))
            category = input("Enter the category (e.g., Rent, Groceries): ")
            self.add_expense(amount, category)
            print(f"Added expense: ${amount} under '{category}' category.")
         elif action == 'save':
            filename = input("Enter the filename to save data (e.g., my_budget.json): ")
            self.save_to_file(filename)
            print(f"Data saved successfully to '{filename}'.")
         elif action == 'load':
            filename = input("Enter the filename to load data (e.g., my_budget.json): ")
            self.load_from_file(filename)
         elif action == 'exit':
            print("Exiting the Budget Tracker. Goodbye!")
            break
         else:
            print("Invalid action. Please try again.")

# Example Usage
tracker = BudgetTracker()
tracker.user_input()

输出

Budget Tracker

之后它将创建加载 -

Budget Tracker

总结

此程序将非常交互地引导用户完成各种选择,并根据用户的选择显示摘要。由于将处理文件,因此数据将成为永久因素。

python_projects_from_basic_to_advanced.htm
广告