
- 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()
輸出

之後它將建立載入 -

總結
此程式將非常互動地引導使用者完成各種選擇,並根據使用者的選擇顯示摘要。由於將處理檔案,因此資料將成為永久因素。