| """Budget tracker: add expenses, see totals per category, saved to budget.json.""" |
| import json |
| from pathlib import Path |
| |
| DATA = Path("budget.json") |
| |
| |
| def load(): |
| return json.loads(DATA.read_text()) if DATA.exists() else [] |
| |
| |
| def save(expenses): |
| DATA.write_text(json.dumps(expenses, indent=2)) |
| |
| |
| def totals(expenses): |
| out = {} |
| for e in expenses: |
| out[e["category"]] = out.get(e["category"], 0) + e["amount"] |
| return out |
| |
| |
| def main(): |
| expenses = load() |
| while True: |
| cmd = input("[a]dd, [r]eport, [q]uit: ").strip().lower() |
| if cmd == "a": |
| category = input("Category: ").strip() or "other" |
| amount = float(input("Amount: ")) |
| expenses.append({"category": category, "amount": amount}) |
| save(expenses) |
| elif cmd == "r": |
| for category, total in sorted(totals(expenses).items()): |
| print(f"{category:<12}{total:>10.2f}") |
| elif cmd == "q": |
| break |
| |
| |
| if __name__ == "__main__": |
| main() |
| |
| # Questions? Ask in the course forum. |