- Python 基础
- Python - 首页
- Python - 概述
- Python - 历史
- Python - 特性
- Python vs C++
- Python - Hello World 程序
- Python - 应用领域
- Python - 解释器
- Python - 环境搭建
- Python - 虚拟环境
- Python - 基本语法
- Python - 变量
- Python - 数据类型
- Python - 类型转换
- Python - Unicode 系统
- Python - 字面量
- Python - 运算符
- Python - 算术运算符
- Python - 比较运算符
- Python - 赋值运算符
- Python - 逻辑运算符
- Python - 位运算符
- Python - 成员运算符
- Python - 身份运算符
- Python - 运算符优先级
- Python - 注释
- Python - 用户输入
- Python - 数字
- Python - 布尔值
- Python 控制语句
- Python - 控制流
- Python - 决策
- Python - if 语句
- Python - if else
- Python - 嵌套 if
- Python - match-case 语句
- Python - 循环
- Python - for 循环
- Python - for-else 循环
- Python - while 循环
- Python - break 语句
- Python - continue 语句
- Python - pass 语句
- Python - 嵌套循环
- Python 函数 & 模块
- Python - 函数
- Python - 默认参数
- Python - 关键字参数
- Python - 仅限关键字参数
- Python - 位置参数
- Python - 仅限位置参数
- Python - 可变参数
- Python - 变量作用域
- Python - 函数注解
- Python - 模块
- Python - 内置函数
- Python 字符串
- Python - 字符串
- Python - 字符串切片
- Python - 修改字符串
- Python - 字符串连接
- Python - 字符串格式化
- Python - 转义字符
- Python - 字符串方法
- Python - 字符串练习
- Python 列表
- Python - 列表
- Python - 访问列表元素
- Python - 修改列表元素
- Python - 添加列表元素
- Python - 删除列表元素
- Python - 循环遍历列表
- Python - 列表推导式
- Python - 对列表排序
- Python - 复制列表
- Python - 合并列表
- Python - 列表方法
- Python - 列表练习
- Python 元组
- Python - 元组
- Python - 访问元组元素
- Python - 更新元组
- Python - 解包元组
- Python - 循环遍历元组
- Python - 合并元组
- Python - 元组方法
- Python - 元组练习
- Python 集合
- Python - 集合
- Python - 访问集合元素
- Python - 添加集合元素
- Python - 删除集合元素
- Python - 循环遍历集合
- Python - 合并集合
- Python - 复制集合
- Python - 集合运算符
- Python - 集合方法
- Python - 集合练习
- Python 字典
- Python - 字典
- Python - 访问字典元素
- Python - 修改字典元素
- Python - 添加字典元素
- Python - 删除字典元素
- Python - 字典视图对象
- Python - 循环遍历字典
- Python - 复制字典
- Python - 嵌套字典
- Python - 字典方法
- Python - 字典练习
- Python 数组
- Python - 数组
- Python - 访问数组元素
- Python - 添加数组元素
- Python - 删除数组元素
- Python - 循环遍历数组
- Python - 复制数组
- Python - 反转数组
- Python - 对数组排序
- Python - 合并数组
- Python - 数组方法
- Python - 数组练习
- Python 文件处理
- Python - 文件处理
- Python - 写入文件
- Python - 读取文件
- Python - 重命名和删除文件
- Python - 目录
- Python - 文件方法
- Python - OS 文件/目录方法
- Python - OS 路径方法
- 面向对象编程
- Python - OOP 概念
- Python - 类 & 对象
- Python - 类属性
- Python - 类方法
- Python - 静态方法
- Python - 构造函数
- Python - 访问修饰符
- Python - 继承
- Python - 多态
- Python - 方法重写
- Python - 方法重载
- Python - 动态绑定
- Python - 动态类型
- Python - 抽象
- Python - 封装
- Python - 接口
- Python - 包
- Python - 内部类
- Python - 匿名类和对象
- Python - 单例类
- Python - 包装类
- Python - 枚举
- Python - 反射
- Python 错误 & 异常
- Python - 语法错误
- Python - 异常
- Python - try-except 代码块
- Python - try-finally 代码块
- Python - 抛出异常
- Python - 异常链
- Python - 嵌套 try 代码块
- Python - 用户自定义异常
- Python - 日志记录
- Python - 断言
- Python - 内置异常
- Python 多线程
- Python - 多线程
- Python - 线程生命周期
- Python - 创建线程
- Python - 启动线程
- Python - 加入线程
- Python - 线程命名
- Python - 线程调度
- Python - 线程池
- Python - 主线程
- Python - 线程优先级
- Python - 守护线程
- Python - 线程同步
- Python 同步
- Python - 线程间通信
- Python - 线程死锁
- Python - 中断线程
- Python 网络编程
- Python - 网络编程
- Python - 套接字编程
- Python - URL 处理
- Python - 泛型
- Python 库
- NumPy 教程
- Pandas 教程
- SciPy 教程
- Matplotlib 教程
- Django 教程
- OpenCV 教程
- Python 杂项
- Python - 日期 & 时间
- Python - 数学
- Python - 迭代器
- Python - 生成器
- Python - 闭包
- Python - 装饰器
- Python - 递归
- Python - 正则表达式
- Python - PIP
- Python - 数据库访问
- Python - 弱引用
- Python - 序列化
- Python - 模板
- Python - 输出格式化
- Python - 性能测量
- Python - 数据压缩
- Python - CGI 编程
- Python - XML 处理
- Python - GUI 编程
- Python - 命令行参数
- Python - 文档字符串
- Python - JSON
- Python - 发送邮件
- Python - 扩展
- Python - 工具/实用程序
- Python - GUI
- Python 高级概念
- Python - 抽象基类
- Python - 自定义异常
- Python - 高阶函数
- Python - 对象内部
- Python - 内存管理
- Python - 元类
- Python - 使用元类进行元编程
- Python - 模拟和存根
- Python - 猴子补丁
- Python - 信号处理
- Python - 类型提示
- Python - 自动化教程
- Python - Humanize 包
- Python - 上下文管理器
- Python - 协程
- Python - 描述符
- Python - 诊断和修复内存泄漏
- Python - 不可变数据结构
- Python 有用资源
- Python - 问答
- Python - 在线测验
- Python - 快速指南
- Python - 参考
- Python - 速查表
- Python - 项目
- Python - 有用资源
- Python - 讨论
- Python 编译器
- NumPy 编译器
- Matplotlib 编译器
- SciPy 编译器
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()
输出
之后它将创建加载 -
总结
此程序将非常交互地引导用户完成各种选择,并根据用户的选择显示摘要。由于将处理文件,因此数据将成为永久因素。