Start learning free

LESSON 32 OF 188 · BACKEND: YOUR FIRST API

Shop Statistics in Python

Practice

A shop owner likes a quick summary of the shop: how many products it has, the lowest and the highest price, and the average price. None of these numbers is stored. Your route works them out from the products on every request, so they always match the shop.

All four come from the list of prices, and Python has a built-in function for each part: len counts the items, min and max find the smallest and the largest, and sum adds them up. The average is the sum divided by the count, and round(x, 2) keeps 2 decimal places. The same functions on other numbers:

ages = [30, 25, 40]
print(len(ages), min(ages), max(ages))   # 3 25 40
print(round(sum(ages) / len(ages), 2))   # 31.67

An empty list has no average: len is 0, and dividing by 0 is an error that crashes the route with a 500. So when the shop has no products, answer the count 0 and None for the other three. jsonify sends None as JSON's null, which means "no value".

Your code must answer these requests, in this order:

GET /stats  →  200  {"count": 4, "cheapest": 2, "most_expensive": 29, "average_price": 12.5}
DELETE /products/1  →  204
GET /stats  →  200  {"count": 3, "cheapest": 2, "most_expensive": 29, "average_price": 12.67}
DELETE /products/2, then /products/3, then /products/4  →  204 each
GET /stats  →  200  {"count": 0, "cheapest": null, "most_expensive": null, "average_price": null}
POST /products  {"name": "Chair", "price": 45, "category": "furniture"}  →  201
GET /stats  →  200  {"count": 1, "cheapest": 45, "most_expensive": 45, "average_price": 45.0}

Your task: add a route for GET /stats that answers count, cheapest, most_expensive and average_price (rounded to 2 places), with null for the last three when the shop is empty.


Assignment
Follow the Coding Tutorial to build the GET /stats route: collect the prices, work out the average, answer the four keys, and handle an empty shop.


Hint
Check for an empty list right after the loop, before you divide. round takes the number first and the number of places second.


STEP 1 OF 9
    Ctrl + Enter to check

    Shop Stats in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free