|
|
這個實驗是 Python 經典的 Budget App(預算管理應用程式),主要練習物件導向程式設計(OOP)、列表(List)、字典(Dictionary)、方法、字串格式化及長條圖繪製。
這題有兩個主要部分:
- Category 類別:管理各個預算分類的存款、提款、餘額及轉帳。
- create_spend_chart() 函式:統計各分類的支出比例,產生文字長條圖。
class Category:
def __init__(self, name):
self.name = name
self.ledger = []
# 存款
def deposit(self, amount, description=""):
self.ledger.append({
"amount": amount,
"description": description
})
# 提款
def withdraw(self, amount, description=""):
if not self.check_funds(amount):
return False
self.ledger.append({
"amount": -amount,
"description": description
})
return True
# 計算目前餘額
def get_balance(self):
return sum(item["amount"] for item in self.ledger)
# 轉帳
def transfer(self, amount, category):
if not self.check_funds(amount):
return False
self.withdraw(amount, f"Transfer to {category.name}")
category.deposit(amount, f"Transfer from {self.name}")
return True
# 檢查餘額是否足夠
def check_funds(self, amount):
return amount <= self.get_balance()
# 列印預算分類內容
def __str__(self):
output = self.name.center(30, "*") + "\n"
for item in self.ledger:
description = item["description"][:23]
amount = item["amount"]
output += f"{description:<23}{amount:>7.2f}\n"
output += f"Total: {self.get_balance():.2f}"
return output
# 建立支出長條圖
def create_spend_chart(categories):
# 計算每個分類的提款金額
spent = []
for category in categories:
total = 0
for item in category.ledger:
if item["amount"] < 0:
total += abs(item["amount"])
spent.append(total)
# 計算所有分類的總支出
total_spent = sum(spent)
# 計算各分類支出百分比,向下取整至 10 的倍數
percentages = []
for amount in spent:
if total_spent == 0:
percentage = 0
else:
percentage = int(amount * 100 / total_spent)
percentage = (percentage // 10) * 10
percentages.append(percentage)
# 建立圖表標題
chart = "Percentage spent by category\n"
# 建立 Y 軸及長條圖
for level in range(100, -1, -10):
chart += f"{level:>3}| "
for percentage in percentages:
if percentage >= level:
chart += "o "
else:
chart += " "
chart += "\n"
# 建立水平線
chart += " " + "-" * (len(categories) * 3 + 1) + "\n"
# 找出最長的分類名稱
max_length = max(len(category.name) for category in categories)
# 垂直顯示分類名稱
for i in range(max_length):
chart += " "
for category in categories:
if i < len(category.name):
chart += category.name + " "
else:
chart += " "
chart += "\n"
return chart.rstrip("\n")
|
|