budget tracker project
commit 8991dbd6a285c571aa024a320b3bd750a403a560
2 changed files with 32 additions and 0 deletions
.gitignore ADDED
View File
| @@ -0,0 +1,2 @@ | ||
| 1 | +budget.json | |
| 2 | +__pycache__/ | |
budget.py ADDED
View File
| @@ -0,0 +1,30 @@ | ||
| 1 | +import json | |
| 2 | +from pathlib import Path | |
| 3 | + | |
| 4 | +DATA = Path("budget.json") | |
| 5 | + | |
| 6 | + | |
| 7 | +def load(): | |
| 8 | + return json.loads(DATA.read_text()) if DATA.exists() else [] | |
| 9 | + | |
| 10 | + | |
| 11 | +def add(expenses, category, amount): | |
| 12 | + expenses.append({"category": category, "amount": amount}) | |
| 13 | + DATA.write_text(json.dumps(expenses, indent=2)) | |
| 14 | + | |
| 15 | + | |
| 16 | +def report(expenses): | |
| 17 | + totals = {} | |
| 18 | + for e in expenses: | |
| 19 | + totals[e["category"]] = totals.get(e["category"], 0) + e["amount"] | |
| 20 | + for cat, total in sorted(totals.items(), key=lambda kv: -kv[1]): | |
| 21 | + print(f"{cat:<12} {total:8.2f}") | |
| 22 | + | |
| 23 | + | |
| 24 | +if __name__ == "__main__": | |
| 25 | + expenses = load() | |
| 26 | + while (cmd := input("add/report/quit: ")) != "quit": | |
| 27 | + if cmd == "add": | |
| 28 | + add(expenses, input("category: "), float(input("amount: "))) | |
| 29 | + elif cmd == "report": | |
| 30 | + report(expenses) | |