These are the notes for Python episode 40, the last episode of the free SyntaxPilot Python course. There is no new topic: we build a real app, kharcha (Hindi for spending), an expense tracker for Asha, and every crash along the way is fixed with something from the course. Text that can't be added becomes a dataclass with float amounts; a typo that kills the app becomes validation + try/except; data that vanishes becomes a JSON file; a growing if/elif becomes a command registry; a wrong report is caught by a unit test; and the whole thing becomes a real command-line tool with argparse, packaged so that python3 -m kharcha runs it. Every program below ran for real (Python 3.13.18); the terminal sessions are from the real package, whose full code is in these notes.
The problem and the plan
Real-life example: Asha writes every rupee she spends in a notebook (chai 20, auto 80, recharge 299). At month end ₹8,000 is gone and, adding pages by hand, she still can't say how much went on food and how much on travel.
Plan on paper before you code:
| Question | Answer for kharcha |
|---|---|
| What will the user type? | commands: add, list, total, report, quit |
| What is one record? | an amount, a category (food, travel, bills...), a note |
| What must never happen? | a typo must not crash the app |
| What must survive? | close the app, open it tomorrow: the data is still there |
| How do we build it? | small steps, running it after every change |
A CLI (command-line interface) is a program you use by typing commands in a terminal, like git, pip or python3 itself.
Version 1: text everywhere (TypeError)
input() reads one line; the program prints each line back (print(">", line)) so we can see it in the output. In the SyntaxPilot compiler, the input goes in the input box, one line per input().
expenses = []
while True:
line = input()
print(">", line)
if line == "quit":
break
parts = line.split()
if parts[0] == "add":
expenses.append(parts[1])
print(" added", parts[1])
elif parts[0] == "total":
print(" total:", sum(expenses))
Input: add 120 food masala chai, add 40 food samosa, total, quit. Output:
> add 120 food masala chai
added 120
> add 40 food samosa
added 40
> total
Traceback (most recent call last):
File "main.py", line 12, in <module>
print(" total:", sum(expenses))
~~~^^^^^^^^^^
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Why: input() always returns a string. parts[1] is the text "120", and sum() starts from the number 0 and can't add text to it. A bare list of words also forgets which word was the category and which was the note.
Version 2: clean records with a dataclass (ValueError)
Real-life example: a printed shop bill. Every line has the same columns (amount, item, type), and the amount is a number the till can add.
A dataclass (episode 27) is a class whose fields are declared with type hints; @dataclass writes __init__, __repr__ and __eq__ for you. Convert the text to a number once, at the door, with float().
from dataclasses import dataclass
@dataclass
class Expense:
amount: float
category: str
note: str
expenses = []
while True:
line = input()
print(">", line)
if line == "quit":
break
parts = line.split()
if parts[0] == "add":
e = Expense(float(parts[1]), parts[2], " ".join(parts[3:]))
expenses.append(e)
print(" added", e)
elif parts[0] == "total":
print(" total: Rs", sum(e.amount for e in expenses))
Output:
> add 120 food masala chai
added Expense(amount=120.0, category='food', note='masala chai')
> add 40 food samosa
added Expense(amount=40.0, category='food', note='samosa')
> total
total: Rs 160.0
> add chai 30
Traceback (most recent call last):
File "main.py", line 17, in <module>
e = Expense(float(parts[1]), parts[2], " ".join(parts[3:]))
~~~~~^^^^^^^^^^
ValueError: could not convert string to float: 'chai'
Why it still fails: add chai 30 puts the words in the wrong order, float("chai") raises ValueError, and nothing catches it. An uncaught exception ends the program: the second total never runs and every expense in memory is lost.
Version 3: survive bad input (validate + try/except)
Real-life example: a bank counter. If you write "chai" in the amount box, the clerk tells you exactly what's wrong and hands the form back; the bank doesn't close because of one bad form.
parse_add only decides what is wrong (it raises a ValueError with a clear message, episode 18); the loop decides what to do about it (print it and carry on). That split makes parse_add easy to test.
from dataclasses import dataclass
@dataclass
class Expense:
amount: float
category: str
note: str
def parse_add(args):
if len(args) < 2:
raise ValueError("usage: add <amount> <category> [note]")
try:
amount = float(args[0])
except ValueError:
raise ValueError(f"amount must be a number, not {args[0]!r}")
return Expense(amount, args[1], " ".join(args[2:]))
expenses = []
while True:
line = input()
print(">", line)
if line == "quit":
break
try:
expenses.append(parse_add(line.split()[1:]))
print(" added. total: Rs", sum(e.amount for e in expenses))
except ValueError as err:
print(" error:", err)
Output:
> add 120 food masala chai
added. total: Rs 120.0
> add chai 30
error: amount must be a number, not 'chai'
> add 40
error: usage: add <amount> <category> [note]
> add 40 food samosa
added. total: Rs 160.0
> quit
{args[0]!r} in an f-string uses repr(), so the bad word is shown in quotes: 'chai'. The final app also refuses zero and negative amounts.
Version 4: remember (JSON files)
To show "close the app and open it again" inside one run, the whole app is a function run_app(day), called once for Monday and once for Tuesday.
from dataclasses import dataclass
@dataclass
class Expense:
amount: float
category: str
note: str
def run_app(day):
print(f"--- {day}: app opened ---")
expenses = []
while True:
line = input()
print(">", line)
if line == "quit":
break
cmd, *args = line.split()
if cmd == "add":
amount, category, *note = args
expenses.append(Expense(float(amount), category, " ".join(note)))
elif cmd == "total":
print(" total: Rs", sum(e.amount for e in expenses))
run_app("Monday") # use the app, then close it
run_app("Tuesday") # open it again the next day
Output:
--- Monday: app opened ---
> add 120 food masala chai
> add 40 food samosa
> total
total: Rs 160.0
> quit
--- Tuesday: app opened ---
> total
total: Rs 0
> quit
Why: a list lives in memory (RAM), and memory is wiped when the program (or here, the function) ends, like a whiteboard cleaned every night. To remember, write to a file (episode 20). JSON is a text format for numbers, strings, lists and dictionaries.
First try: json.dump the list of Expense objects
import json, os
from dataclasses import dataclass, asdict
@dataclass
class Expense:
amount: float
category: str
note: str
FILE = "kharcha.json"
def load():
if not os.path.exists(FILE): # first day: no file yet
return []
with open(FILE) as f:
return [Expense(**d) for d in json.load(f)]
def save(expenses):
with open(FILE, "w") as f:
json.dump(expenses, f)
# Monday: open the app, add two, close it
book = load()
book += [Expense(120, "food", "masala chai"), Expense(40, "food", "samosa")]
save(book)
book = load() # Tuesday: open it again
print(len(book), "expenses, total Rs", sum(e.amount for e in book))
print(book[0])
Output (the end of the traceback):
TypeError: Object of type Expense is not JSON serializable
JSON only knows numbers, strings, lists, dictionaries, true, false and null. It has no idea what an Expense is.
The fix: asdict() out, Expense(**d) back in
import json, os
from dataclasses import dataclass, asdict
@dataclass
class Expense:
amount: float
category: str
note: str
FILE = "kharcha.json"
def load():
if not os.path.exists(FILE): # first day: no file yet
return []
with open(FILE) as f:
return [Expense(**d) for d in json.load(f)]
def save(expenses):
with open(FILE, "w") as f:
json.dump([asdict(e) for e in expenses], f)
# Monday: open the app, add two, close it
book = load()
book += [Expense(120, "food", "masala chai"), Expense(40, "food", "samosa")]
save(book)
book = load() # Tuesday: open it again
print(len(book), "expenses, total Rs", sum(e.amount for e in book))
print(book[0])
Output:
2 expenses, total Rs 160
Expense(amount=120, category='food', note='masala chai')
asdict(e)(fromdataclasses) turns an Expense into a plain dict:{'amount': 120, 'category': 'food', 'note': 'masala chai'}.Expense(**d)unpacks the dict into keyword arguments:Expense(amount=120, category='food', note='masala chai').os.path.exists(FILE)handles the very first day, when there is no file yet (otherwiseopen()raisesFileNotFoundError).
Pro tip (used in the final app): if the power goes out in the middle of json.dump, the file is left half-written and the next json.load fails with json.decoder.JSONDecodeError. So the real save() writes to kharcha.json.tmp first and then swaps it in with os.replace(), which replaces the old file in one step.
A command registry
The problem: one loop handling add, total, list, report and a help menu becomes a long if/elif, and each command needs its own copy-pasted checks for missing or extra words.
Real-life example (episode 39): the chai stall's menu card: item name → how to make it. A registry is a dict from command name to function, filled by a decorator (episode 25).
COMMANDS = {}
def command(fn): # a registering decorator
COMMANDS[fn.__name__] = fn
return fn
@command
def add(book, amount, category, *note):
"""<amount> <category> [note]"""
book.append((float(amount), category, " ".join(note)))
return f"added Rs {float(amount):.0f}"
@command
def total(book):
"""the total spent"""
return f"total: Rs {sum(e[0] for e in book):.0f}"
@command
def menu(book):
"""list every command"""
return "\n ".join(f"{n:<6}{f.__doc__}" for n, f in COMMANDS.items())
def handle(book, line):
name, *args = line.split()
if name not in COMMANDS:
return f"unknown command {name!r}, try 'menu'"
try:
return COMMANDS[name](book, *args)
except (ValueError, TypeError) as err:
return f"error: {err}"
book = []
for line in ["menu", "add 120 food chai", "add 50", "pay 10", "total"]:
print(">", line, "\n ", handle(book, line))
Output:
> menu
add <amount> <category> [note]
total the total spent
menu list every command
> add 120 food chai
added Rs 120
> add 50
error: add() missing 1 required positional argument: 'category'
> pay 10
unknown command 'pay', try 'menu'
> total
total: Rs 120
fn.__name__is the function's own name, so@commandregistersaddunder"add".- Each docstring (
"""...""") is that command's help text;menubuilds the help from the dict, so it can never go out of date. COMMANDS[name](book, *args)calls the chosen function with the words as arguments. If a word is missing, Python's own call check raisesTypeError: add() missing 1 required positional argument: 'category', and theexceptturns it into a friendly message. The function's parameters are the validation.- To keep the screen small, expenses here are tuples
(amount, category, note); the final app uses the dataclass.
Tests catch a real bug
report() adds up spending per category with a dict and get() (episode 12). Before trusting it with money, test it with unittest (episode 29):
import unittest
def report(book): # book: [(amount, category), ...]
totals = {}
for amount, category in book:
totals[category] = totals.get(category, 0) + amount
return totals
class TestReport(unittest.TestCase):
def test_adds_up_each_category(self):
book = [(120, "food"), (40, "food"), (300, "travel")]
self.assertEqual(report(book), {"food": 160, "travel": 300})
def test_capitals_same_category(self):
book = [(120, "food"), (40, "Food")]
self.assertEqual(report(book), {"food": 160})
unittest.main()
Output:
.F
======================================================================
FAIL: test_capitals_same_category (__main__.TestReport.test_capitals_same_category)
----------------------------------------------------------------------
Traceback (most recent call last):
File "main.py", line 16, in test_capitals_same_category
self.assertEqual(report(book), {"food": 160})
~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: {'food': 120, 'Food': 40} != {'food': 160}
- {'Food': 40, 'food': 120}
+ {'food': 160}
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (failures=1)
.F means one test passed and one failed. Asha types Food with a capital F sometimes, and 'food' and 'Food' are different dict keys. The fix is one line: clean the category on the way in.
import unittest
def report(book): # book: [(amount, category), ...]
totals = {}
for amount, category in book:
category = category.strip().lower()
totals[category] = totals.get(category, 0) + amount
return totals
class TestReport(unittest.TestCase):
def test_adds_up_each_category(self):
book = [(120, "food"), (40, "food"), (300, "travel")]
self.assertEqual(report(book), {"food": 160, "travel": 300})
def test_capitals_same_category(self):
book = [(120, "food"), (40, "Food")]
self.assertEqual(report(book), {"food": 160})
unittest.main()
Output:
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
In the final app, add() does the cleaning (category.strip().lower()), so every category is stored the same way, and the test stays forever: if anyone breaks the rule, the test fails before Asha's report does.
A real CLI with argparse
In a terminal you type the whole command at once: python3 kharcha.py add 120 food masala chai. Python puts the words after the file name in sys.argv, a list of strings: ['kharcha.py', 'add', '120', 'food', 'masala', 'chai']. You could parse it by hand, but the standard library's argparse checks the words, converts types, and writes --help for you. Sub-commands (add, total) work like git commit and pip install.
The compiler can't pass words after the file name, so we give parse_args() the list directly:
import argparse
parser = argparse.ArgumentParser(prog="kharcha",
description="Asha's expense tracker")
sub = parser.add_subparsers(dest="command", required=True)
add = sub.add_parser("add", help="add an expense")
add.add_argument("amount", type=float, help="in rupees")
add.add_argument("category")
add.add_argument("note", nargs="*")
sub.add_parser("total", help="show the total spent")
# in a terminal: python3 kharcha.py add 120 food masala chai
args = parser.parse_args(["add", "120", "food", "masala", "chai"])
print(args)
args = parser.parse_args(["add", "chai", "food"])
print("never printed")
Output:
Namespace(command='add', amount=120.0, category='food', note=['masala', 'chai'])
usage: kharcha add [-h] amount category [note ...]
kharcha add: error: argument amount: invalid float value: 'chai'
- The good command becomes a Namespace:
args.command,args.amount(already a float, because oftype=float),args.category,args.note(a list, because ofnargs="*", "zero or more words"). - The bad one prints the usage line and
error: argument amount: invalid float value: 'chai', then exits with exit code 2, which tells the terminal the command failed.print("never printed")never runs.
And --help is generated for free:
import argparse
parser = argparse.ArgumentParser(prog="kharcha",
description="Asha's expense tracker")
sub = parser.add_subparsers(dest="command", required=True)
add = sub.add_parser("add", help="add an expense")
add.add_argument("amount", type=float, help="in rupees")
add.add_argument("category")
add.add_argument("note", nargs="*")
sub.add_parser("total", help="show the total spent")
# in a terminal: python3 kharcha.py add 120 food masala chai
args = parser.parse_args(["add", "120", "food", "masala", "chai"])
print(args)
args = parser.parse_args(["--help"])
Output:
Namespace(command='add', amount=120.0, category='food', note=['masala', 'chai'])
usage: kharcha [-h] {add,total} ...
Asha's expense tracker
positional arguments:
{add,total}
add add an expense
total show the total spent
options:
-h, --help show this help message and exit
The finished app: one job per file
kharcha/
├── kharcha/
│ ├── __init__.py
│ ├── __main__.py ← python3 -m kharcha
│ ├── models.py ← Expense dataclass
│ ├── storage.py ← load() / save() JSON
│ ├── commands.py ← add, total, list, report
│ └── cli.py ← argparse
├── tests/
│ ├── __init__.py
│ └── test_commands.py
└── README.md
Each file imports only what it needs: storage knows nothing about argparse, and commands knows nothing about files, which is why report() could be tested without touching a file. A package is a folder of modules with an __init__.py (episode 19); __main__.py is what runs for python3 -m kharcha.
kharcha/init.py
"""kharcha: Asha's expense tracker."""
kharcha/models.py
from dataclasses import dataclass
@dataclass
class Expense:
amount: float
category: str
note: str = ""
kharcha/storage.py
import json
import os
from dataclasses import asdict
from .models import Expense
FILE = os.environ.get("KHARCHA_FILE", "kharcha.json")
def load():
if not os.path.exists(FILE): # first run: no file yet
return []
with open(FILE) as f:
return [Expense(**d) for d in json.load(f)]
def save(book):
tmp = FILE + ".tmp" # write a copy, then swap it in
with open(tmp, "w") as f:
json.dump([asdict(e) for e in book], f, indent=1)
os.replace(tmp, FILE)
KHARCHA_FILE lets you point the app at another file (KHARCHA_FILE=test.json python3 -m kharcha list), handy for experiments.
kharcha/commands.py
from .models import Expense
def parse_amount(text):
try:
amount = float(text)
except ValueError:
raise ValueError(f"amount must be a number, not {text!r}")
if amount <= 0:
raise ValueError("amount must be more than 0")
return amount
def add(book, amount, category, note=""):
e = Expense(parse_amount(amount), category.strip().lower(), note)
book.append(e)
return f"added Rs {e.amount:.0f} to {e.category}"
def total(book):
return f"total: Rs {sum(e.amount for e in book):.0f} in {len(book)} expenses"
def report(book):
totals = {}
for e in book:
totals[e.category] = totals.get(e.category, 0) + e.amount
return totals
def report_text(book):
totals = report(book)
if not totals:
return "no expenses yet"
grand = sum(totals.values())
lines = []
for cat, amt in sorted(totals.items(), key=lambda kv: kv[1], reverse=True):
bar = "#" * round(20 * amt / grand)
lines.append(f"{cat:<9} Rs {amt:>6.0f} {bar} {100 * amt / grand:.0f}%")
return "\n".join(lines)
def list_text(book):
if not book:
return "no expenses yet"
return "\n".join(f"{i:>2}. Rs {e.amount:>6.0f} {e.category:<9} {e.note}"
for i, e in enumerate(book, 1))
report_text sorts with a lambda key (episode 17), largest first, and draws a bar of # out of 20.
kharcha/cli.py
import argparse
from . import commands, storage
def build_parser():
parser = argparse.ArgumentParser(prog="kharcha", description="Asha's expense tracker")
sub = parser.add_subparsers(dest="command", required=True)
add = sub.add_parser("add", help="add an expense")
add.add_argument("amount", help="in rupees, e.g. 120")
add.add_argument("category", help="food, travel, bills...")
add.add_argument("note", nargs="*", help="what it was")
sub.add_parser("list", help="every expense")
sub.add_parser("total", help="the total spent")
sub.add_parser("report", help="spend per category")
return parser
def main(argv=None):
args = build_parser().parse_args(argv)
book = storage.load()
try:
if args.command == "add":
print(commands.add(book, args.amount, args.category, " ".join(args.note)))
storage.save(book)
elif args.command == "list":
print(commands.list_text(book))
elif args.command == "total":
print(commands.total(book))
elif args.command == "report":
print(commands.report_text(book))
except ValueError as err:
print("error:", err)
return 1
return 0
kharcha/main.py
import sys
from .cli import main
sys.exit(main())
tests/test_commands.py (plus an empty tests/__init__.py, so python3 -m unittest finds the folder)
import unittest
from kharcha.commands import add, report
class TestKharcha(unittest.TestCase):
def test_report_adds_up_each_category(self):
book = []
add(book, "120", "food")
add(book, "40", "food")
add(book, "300", "travel")
self.assertEqual(report(book), {"food": 160, "travel": 300})
def test_capitals_are_the_same_category(self):
book = []
add(book, "120", "food")
add(book, "40", "Food")
self.assertEqual(report(book), {"food": 160})
def test_bad_amount_is_refused(self):
with self.assertRaises(ValueError):
add([], "chai", "food")
if __name__ == "__main__":
unittest.main()
Running it in a real terminal
Run these from the outer kharcha/ folder. Each command is a new run of Python; the data survives in kharcha.json.
asha@laptop:~/kharcha$ python3 -m kharcha add 120 food masala chai
added Rs 120 to food
asha@laptop:~/kharcha$ python3 -m kharcha add 40 Food samosa
added Rs 40 to food
asha@laptop:~/kharcha$ python3 -m kharcha add 300 travel auto to office
added Rs 300 to travel
asha@laptop:~/kharcha$ python3 -m kharcha add 1499 bills phone recharge
added Rs 1499 to bills
asha@laptop:~/kharcha$ python3 -m kharcha add chai 30
error: amount must be a number, not 'chai'
asha@laptop:~/kharcha$ python3 -m kharcha list
1. Rs 120 food masala chai
2. Rs 40 food samosa
3. Rs 300 travel auto to office
4. Rs 1499 bills phone recharge
asha@laptop:~/kharcha$ python3 -m kharcha total
total: Rs 1959 in 4 expenses
asha@laptop:~/kharcha$ python3 -m kharcha report
bills Rs 1499 ############### 77%
travel Rs 300 ### 15%
food Rs 160 ## 8%
asha@laptop:~/kharcha$ python3 -m kharcha remove 2
usage: kharcha [-h] {add,list,total,report} ...
kharcha: error: argument command: invalid choice: 'remove' (choose from 'add', 'list', 'total', 'report')
asha@laptop:~/kharcha$ python3 -m unittest
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
The report answers Asha's real question: bills (the phone recharge) were 77% of her spending, not chai.
Common mistakes
| Mistake | What you see | Why | Fix |
|---|---|---|---|
sum() of the text from input() |
TypeError: unsupported operand type(s) for +: 'int' and 'str' |
input() always gives a str |
float(text) once, at the door |
float("chai") with no try |
ValueError: could not convert string to float: 'chai' |
one typo ends the program | validate, and try/except in the loop |
| data only in a list | total: Rs 0 the next day |
memory is wiped at exit | save to / load from a file |
json.dump(expenses, f) |
TypeError: Object of type Expense is not JSON serializable |
JSON doesn't know your class | asdict(e) out, Expense(**d) in |
json.load of a half-written file |
json.decoder.JSONDecodeError: Expecting value |
the save was interrupted | write a temp file, then os.replace |
| categories stored as typed | AssertionError: {'food': 120, 'Food': 40} != {'food': 160} |
'Food' and 'food' are different keys |
.strip().lower() on the way in |
open(FILE) on the first day |
FileNotFoundError: [Errno 2] No such file or directory: 'kharcha.json' |
the file doesn't exist yet | os.path.exists(FILE) check |
| a wrong word in the terminal | error: argument amount: invalid float value: 'chai' (exit code 2) |
argparse checked it | read the usage line |
python3 -m unittest finds nothing |
NO TESTS RAN |
tests/ has no __init__.py |
add an empty tests/__init__.py |
Your turn: make kharcha yours (solution)
Homework: (1) remove <number> with a check that the number exists, (2) a date on every expense, (3) a monthly report, (4) a budget warning, and a test for every new command. Here is the full solution for remove; dates, monthly reports and budgets follow the same pattern (a new field in Expense, a new function in commands.py, a new sub-parser in cli.py, a new test).
Solution: remove
Add to commands.py:
def remove(book, number):
try:
i = int(number)
except ValueError:
raise ValueError(f"number must be a whole number, not {number!r}")
if not 1 <= i <= len(book):
raise ValueError(f"no expense number {i} (there are {len(book)})")
e = book.pop(i - 1)
return f"removed Rs {e.amount:.0f} {e.category} {e.note}".rstrip()
In cli.py, a sub-parser and a branch that saves:
rm = sub.add_parser("remove", help="delete one expense")
rm.add_argument("number", help="its number in 'list'")
elif args.command == "remove":
print(commands.remove(book, args.number))
storage.save(book)
A test in tests/test_commands.py (import remove too):
def test_remove_checks_the_number(self):
book = []
add(book, "120", "food", "chai")
with self.assertRaises(ValueError):
remove(book, "2")
self.assertEqual(remove(book, "1"), "removed Rs 120 food chai")
self.assertEqual(book, [])
Real session:
asha@laptop:~/kharcha$ python3 -m kharcha add 120 food masala chai
added Rs 120 to food
asha@laptop:~/kharcha$ python3 -m kharcha add 40 food samosa
added Rs 40 to food
asha@laptop:~/kharcha$ python3 -m kharcha remove 5
error: no expense number 5 (there are 2)
asha@laptop:~/kharcha$ python3 -m kharcha remove two
error: number must be a whole number, not 'two'
asha@laptop:~/kharcha$ python3 -m kharcha remove 1
removed Rs 120 food masala chai
asha@laptop:~/kharcha$ python3 -m kharcha list
1. Rs 40 food samosa
asha@laptop:~/kharcha$ python3 -m unittest
....
----------------------------------------------------------------------
Ran 4 tests in 0.000s
OK
list numbers start at 1 for people; book.pop(i - 1) converts back to Python's 0-based index.
Hints: date, monthly report, budget
- Date: add
date: str = ""toExpenseand fill it withdatetime.date.today().isoformat()(e.g."2026-11-07") inadd. Old JSON files without a date still load, because the field has a default. - Monthly report:
report --month 2026-11→ filter[e for e in book if e.date.startswith(month)]beforereport(). - Budget: keep budgets in a second JSON file,
{"food": 3000}; after eachadd, comparereport(book)[category]with the budget and print a warning. - Write each feature's test first, watch it fail, then make it pass.
Practice
1. What does this print?
from dataclasses import dataclass, asdict
@dataclass
class Expense:
amount: float
category: str
note: str = ""
print(asdict(Expense(40, "food")))
Answer
{'amount': 40, 'category': 'food', 'note': ''}
note uses its default, and amount stays the int 40 (type hints don't convert values).
2. Add an average command to the registry version that prints the average expense, and says "no expenses yet" for an empty book.
Solution
COMMANDS = {}
def command(fn):
COMMANDS[fn.__name__] = fn
return fn
@command
def add(book, amount, category, *note):
"""<amount> <category> [note]"""
book.append((float(amount), category, " ".join(note)))
return f"added Rs {float(amount):.0f}"
@command
def average(book):
"""the average expense"""
if not book:
return "no expenses yet"
return f"average: Rs {sum(e[0] for e in book) / len(book):.2f}"
book = []
for line in ["average", "add 120 food chai", "add 45 travel bus", "average"]:
name, *args = line.split()
print(">", line, "\n ", COMMANDS[name](book, *args))
Output:
> average
no expenses yet
> add 120 food chai
added Rs 120
> add 45 travel bus
added Rs 45
> average
average: Rs 82.50
3. Why does save() write to a .tmp file and then call os.replace()?
Answer
So the real file is never half-written. If the program dies during json.dump, only the temp file is damaged; the old kharcha.json is untouched. os.replace swaps the files in one step (it is atomic on the same disk), so the next load() sees either the old data or the new data, never a mix.
4. Make argparse refuse amounts that aren't positive, using a custom type function.
Solution
import argparse
def positive(text):
value = float(text) # "chai" -> ValueError -> argparse error
if value <= 0:
raise argparse.ArgumentTypeError(f"{text} is not more than 0")
return value
parser = argparse.ArgumentParser(prog="kharcha")
parser.add_argument("amount", type=positive)
print(parser.parse_args(["120"]))
parser.parse_args(["-5"])
Output:
Namespace(amount=120.0)
usage: kharcha [-h] amount
kharcha: error: argument amount: -5 is not more than 0
argparse calls the type function on the word; a ValueError or ArgumentTypeError becomes a clean usage error with exit code 2.
5. Test parse_amount from commands.py for "120", "12.5", "chai", "0" and "-5".
Solution
import unittest
def parse_amount(text):
try:
amount = float(text)
except ValueError:
raise ValueError(f"amount must be a number, not {text!r}")
if amount <= 0:
raise ValueError("amount must be more than 0")
return amount
class TestParseAmount(unittest.TestCase):
def test_good(self):
self.assertEqual(parse_amount("120"), 120.0)
self.assertEqual(parse_amount("12.5"), 12.5)
def test_bad(self):
for text in ["chai", "0", "-5"]:
with self.subTest(text=text):
with self.assertRaises(ValueError):
parse_amount(text)
unittest.main()
Output:
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
subTest reports each bad input separately if one of them ever fails.
Quick quiz
What does this print?
import json
from dataclasses import dataclass, asdict
@dataclass
class Expense:
amount: float
category: str
e = Expense(40, "food")
text = json.dumps(asdict(e))
print(Expense(**json.loads(text)) == e)
(A) True (B) False (C) TypeError (D) {'amount': 40, 'category': 'food'}
Answer
(A) True. asdict makes a dict, json.dumps / json.loads write it as text and read it back, Expense(**d) rebuilds the object, and dataclasses compare field by field. That's save and load in two lines.
True
Interview questions
- Walk me through a project you built. Problem (Asha can't see where money goes) → plan (commands, record, rules) → versions, each fixing a real failure → tests → packaging. Interviewers want the why behind each decision.
- Why validate input at the boundary? So the rest of the code can trust its data; errors are reported once, clearly, where they enter.
- How do you store a dataclass in JSON?
json.dump([asdict(e) for e in book], f), and load with[Expense(**d) for d in json.load(f)]. - How do you avoid a corrupted save file? Write a temporary file, then
os.replace()it over the real one. - What is the difference between
sys.argvand argparse?sys.argvis the raw list of words; argparse defines the expected arguments, converts and checks them, and generates usage and help. - What is an exit code? A number a program returns to the terminal: 0 means success, anything else means failure (argparse uses 2 for usage errors).
sys.exit(main())passesmain()'s return value on. - What does
python3 -m kharchado? Runs the package's__main__.pyas a module, with the current folder on the import path, so relative imports likefrom . import commandswork. - Why separate
commands.pyfromcli.pyandstorage.py? Each has one job, can be tested on its own, and can be swapped (a web UI could reusecommands.pyunchanged). - How did a test help in this project? It caught
'Food'vs'food'before real data did. - What would you add next? Dates and monthly reports, budgets,
remove/edit, a SQLite database (Python'ssqlite3) instead of JSON for many records, and packaging withpyproject.tomlsopip install .gives akharchacommand.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Capstone project | A final project that uses everything from a course | kharcha |
| CLI (command-line interface) | A program used by typing commands in a terminal | git, pip, python3 -m kharcha |
| Terminal | The text window where you type commands | asha@laptop:~/kharcha$ |
input() |
Reads one line from the user (or stdin), always as a str | input() → "add 120 food" |
str.split() |
Cuts a string into words at spaces | "add 120".split() → ['add', '120'] |
| Star unpacking | first, *rest = list puts the leftovers in a list |
cmd, *args = line.split() |
| Dataclass | A class whose fields are declared with type hints; @dataclass writes __init__, __repr__, __eq__ |
@dataclass class Expense |
| Validation | Checking input before using it | amount must be a number > 0 |
raise |
Signals an error by creating an exception | raise ValueError("...") |
| try / except | Runs code and handles an exception instead of crashing | the loop keeps going after a typo |
!r in an f-string |
Shows the value with repr(), so strings get quotes |
f"{'chai'!r}" → 'chai' |
| RAM (memory) | Where a running program keeps its variables; wiped at exit | the expenses list |
| Persistence | Keeping data after the program ends | saving to kharcha.json |
| JSON | A text format for numbers, strings, lists, dicts, true/false/null | [{"amount": 120}] |
json.dump / json.load |
Write Python data to a file as JSON / read it back | json.dump(data, f) |
| Serializable | Can be turned into a format like JSON | dicts yes, your own classes no |
asdict() |
Turns a dataclass object into a dict | asdict(e) |
**d (dict unpacking) |
Passes a dict's items as keyword arguments | Expense(**d) |
os.path.exists() |
True if a file or folder exists | the first-day check |
os.replace() |
Moves a file over another in one step | the safe save |
| Atomic | Happens completely or not at all | os.replace on the same disk |
| Registry | A dict from names to functions, filled by a decorator | COMMANDS |
| Decorator | A function that takes a function and returns one, written @name |
@command |
__name__ (of a function) |
The function's own name | add.__name__ → 'add' |
| Docstring | A string right under def, documenting the function |
"""the total spent""" |
| Unit test | A small automatic check of one piece of code | test_capitals_same_category |
assertEqual |
Fails the test if two values differ | self.assertEqual(a, b) |
assertRaises |
Fails the test unless the code raises that exception | with self.assertRaises(ValueError): |
sys.argv |
The list of words typed after python3 |
['kharcha.py', 'add', '120'] |
| argparse | The standard-library module for command-line arguments | ArgumentParser |
| Sub-command | A command word that picks an action | add, list, report |
| Namespace | The object argparse returns, with one attribute per argument | args.amount |
nargs="*" |
Zero or more words for one argument, as a list | the note |
| Exit code | The number a program returns: 0 = success | argparse errors exit with 2 |
| Package | A folder of modules with __init__.py |
kharcha/ |
__main__.py |
The file python3 -m package runs |
python3 -m kharcha |
| Relative import | Import from the same package with a dot | from . import commands |
Summary
- Plan first: the commands, one record, and the rules (no crash on typos, data survives).
input()gives text: convert once, at the door, into a dataclass with real numbers.- Validate in one function (raise
ValueErrorwith a clear message) and catch in the loop, so one typo never kills the app. - Memory is wiped at exit: save to JSON with
asdict, load withExpense(**d), and save safely with a temp file +os.replace. - A command registry (a dict of functions filled by a decorator) replaces a growing if/elif; function parameters do the argument checking.
- Tests find bugs before users do:
'Food'vs'food'was caught byunittest. - argparse turns it into a real CLI with type checks, sub-commands and
--help; a package with__main__.pyruns aspython3 -m kharcha. - Every concept in the course is a tool for a real problem. Keep building.
Next on SyntaxPilot: Python Coding Questions, interview practice with three questions an episode, starting with Number questions I: reverse a number, palindrome number, sum of digits.