Add lesson 10: Project: budget tracker
3 changed files with 64 additions and 0 deletions
lessons/10-project-budget-tracker/README.md ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +# Lesson 10: Project: budget tracker | |
| 2 | + | |
| 3 | +This lesson covers project: budget tracker. You'll read a short explanation, try three small exercises and finish with a quiz. | |
| 4 | + | |
| 5 | +Full lesson: [https://glibcode.net/courses/python-basics/lessons/10](https://glibcode.net/courses/python-basics/lessons/10) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `budget.py`: the course project: a budget tracker that saves to JSON | |
| 10 | + | |
| 11 | +## Run it | |
| 12 | + | |
| 13 | +```sh | |
| 14 | +python3 budget.py | |
| 15 | +``` | |
| 16 | + | |
| 17 | +## Exercises | |
| 18 | + | |
| 19 | +See [exercises.md](exercises.md). Ask in the forum once you've tried. | |
lessons/10-project-budget-tracker/budget.py ADDED
| @@ -0,0 +1,40 @@ | ||
| 1 | +"""Budget tracker: add expenses, see totals per category, saved to budget.json.""" | |
| 2 | +import json | |
| 3 | +from pathlib import Path | |
| 4 | + | |
| 5 | +DATA = Path("budget.json") | |
| 6 | + | |
| 7 | + | |
| 8 | +def load(): | |
| 9 | + return json.loads(DATA.read_text()) if DATA.exists() else [] | |
| 10 | + | |
| 11 | + | |
| 12 | +def save(expenses): | |
| 13 | + DATA.write_text(json.dumps(expenses, indent=2)) | |
| 14 | + | |
| 15 | + | |
| 16 | +def totals(expenses): | |
| 17 | + out = {} | |
| 18 | + for e in expenses: | |
| 19 | + out[e["category"]] = out.get(e["category"], 0) + e["amount"] | |
| 20 | + return out | |
| 21 | + | |
| 22 | + | |
| 23 | +def main(): | |
| 24 | + expenses = load() | |
| 25 | + while True: | |
| 26 | + cmd = input("[a]dd, [r]eport, [q]uit: ").strip().lower() | |
| 27 | + if cmd == "a": | |
| 28 | + category = input("Category: ").strip() or "other" | |
| 29 | + amount = float(input("Amount: ")) | |
| 30 | + expenses.append({"category": category, "amount": amount}) | |
| 31 | + save(expenses) | |
| 32 | + elif cmd == "r": | |
| 33 | + for category, total in sorted(totals(expenses).items()): | |
| 34 | + print(f"{category:<12}{total:>10.2f}") | |
| 35 | + elif cmd == "q": | |
| 36 | + break | |
| 37 | + | |
| 38 | + | |
| 39 | +if __name__ == "__main__": | |
| 40 | + main() | |
lessons/10-project-budget-tracker/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 10 | |
| 2 | + | |
| 3 | +1. Break the example on purpose: delete a bracket or misspell a name. Read the error message. Which line does it point to? | |
| 4 | +2. Combine this lesson with the previous one: use something from both in a small program of your own. | |
| 5 | +3. Explain the example to someone who hasn't taken the course. Which part was hardest to explain? | |