A draft that draws the metrics before checking for an empty choice

Code review · Medium · §11.4 Checking numbers and diagnosing errors

This is an AI draft of an app that shows weekly visits to each room of a gym. When you clear all the rooms, two metrics showing 0 and 0 rows are drawn first, and only then does the warning appear.

Fix it by moving lines so that an empty choice shows only the warning, with no metrics, and stops. Grading runs the app again with different rooms and weeks, and with all the rooms cleared.

Target figure for A draft that draws the metrics before checking for an empty choice
Target figure

Code to fix

import pandas as pd
import streamlit as st

gym = pd.DataFrame({
    "week": [1, 2, 3, 4] * 3,
    "room": ["Weights"] * 4 + ["Pool"] * 4 + ["Yoga"] * 4,
    "visits": [310, 295, 340, 362, 120, 135, 128, 150, 88, 95, 102, 110],
})
st.title("Gym visits")
rooms = st.sidebar.multiselect("Room", ["Weights", "Pool", "Yoga"], default=["Weights", "Pool", "Yoga"])
weeks = st.sidebar.slider("Week", 1, 4, (1, 4))
view = gym[gym["room"].isin(rooms) & gym["week"].between(weeks[0], weeks[1])]

c1, c2 = st.columns(2)
c1.metric("Visits", f"{view['visits'].sum():,}")
c2.metric("Rows", f"{len(view)} rows")
if view.empty:
    st.warning("No visits to show. Pick at least one room.")
    st.stop()
st.dataframe(view, hide_index=True)

Solve this problem in your browser

Python runs in your browser and checks your answer right away. Hints and the answer are on the problem page.