#612 · Errors and exceptions · Advanced · 115 XP · about 20 min
An online shop receives orders as nested dictionaries and lists. When an order is broken, the error should point to the exact place, like items[1].qty, so the person who sent it knows what to fix.
OrderError is provided: OrderError(path, problem) has the attributes path and problem, and its message is 'path: problem'.
Write order_total(order) that checks the order and returns its total, the sum of qty * price over all items, rounded to 2 decimal places. At the first problem, raise OrderError with the path and problem shown here. Check in this order:
order must be a dictionary: 'order', 'must be a dict'.order['id'] must be a string that is not empty: 'id', 'must be a non-empty string'.order['items'] must be a list that is not empty: 'items', 'must be a non-empty list'.Then, for each item, where i is its index counting from 0:
'items[i]', 'must be a dict'.name must be a string that is not empty: 'items[i].name', 'must be a non-empty string'.qty must be an int of at least 1: 'items[i].qty', 'must be a whole number of at least 1'.price must be an int or a float of at least 0: 'items[i].price', 'must be a number of at least 0'.A missing key counts as a wrong value. True and False are not numbers here, even though Python treats them as 1 and 0.
order_total({'id': 'A7', 'items': [{'name': 'pen', 'qty': 3, 'price': 1.5}, {'name': 'pad', 'qty': 1, 'price': 4}]}) # returns 8.5 order_total({'id': 'A7', 'items': [{'name': 'pen', 'qty': 3, 'price': 1.5}, {'name': 'pad', 'qty': 0, 'price': 4}]}) # raises OrderError: items[1].qty: must be a whole number of at least 1 order_total({'items': []}) # raises OrderError: id: must be a non-empty string
First solves only, ranked by stars and then time.