Quiz: Streamlit Dashboards


Part I: Multiple Choice (10 questions)

Q1. How is a Streamlit app run?

A) Inside a Jupyter notebook B) streamlit run app.py from the command line C) python app.py from the command line D) Double-click the file

Answer**B.** Streamlit apps are run with `streamlit run app.py` from a terminal. They cannot run from Jupyter — the execution model is incompatible.

Q2. What happens when a user interacts with a widget in a Streamlit app?

A) A callback function is called B) The widget's value changes silently C) The entire script re-runs from top to bottom D) A new page loads

Answer**C.** Streamlit's execution model re-runs the entire script on every interaction. Caching prevents expensive operations from re-running.

Q3. Which decorator caches a DataFrame-returning function?

A) @st.memoize B) @st.cache_data C) @st.store D) @functools.lru_cache

Answer**B.** `@st.cache_data` is for serializable data like DataFrames. For unserializable objects (database connections, ML models), use `@st.cache_resource`.

Q4. Which function embeds a Plotly figure in Streamlit?

A) st.plot(fig) B) st.plotly_chart(fig) C) st.plotly(fig) D) st.show(fig)

Answer**B.** `st.plotly_chart(fig, use_container_width=True)` is the standard pattern. `use_container_width=True` makes the chart responsive.

Q5. How do you add controls to the sidebar?

A) st.left_panel.slider(...) B) st.sidebar.slider(...) or with st.sidebar: block C) st.panel("left").slider(...) D) sidebar(slider(...))

Answer**B.** Either `st.sidebar.slider(...)` (as a method) or `with st.sidebar: ...` (as a context manager) adds widgets to the sidebar.

Q6. What is st.session_state?

A) A database connection B) A dictionary that persists across re-runs for the user's session C) An event handler D) A styling theme

Answer**B.** `st.session_state` is a dict-like object that survives re-runs. Use it for values that must persist (counters, multi-step workflows, persistent selections).

Q7. Which layout primitive creates horizontal columns?

A) st.columns(n) B) st.grid(n) C) st.row(n) D) st.split(n)

Answer**A.** `col1, col2, col3 = st.columns(3)` creates three equal-width columns. You can also pass a list of widths: `st.columns([2, 1, 1])`.

Q8. What is Streamlit Community Cloud?

A) A paid hosting service B) A free hosting service that deploys apps from GitHub C) A local development environment D) A database

Answer**B.** Streamlit Community Cloud (share.streamlit.io) hosts Streamlit apps for free by connecting to GitHub repositories. Push code to GitHub, click a few buttons, and the app is live.

Q9. What is the purpose of st.form?

A) To validate user input B) To batch widget interactions so only a submit button triggers a re-run C) To style widgets D) To save data to a database

Answer**B.** Widgets inside a `st.form` do not trigger re-runs on change. Only the submit button re-runs the script, batching all widget values at once. Useful for dashboards with expensive downstream computations.

Q10. The chapter's threshold concept is:

A) Dashboards should be static B) Apps are scripts C) Caching is optional D) Streamlit replaces matplotlib

Answer**B.** Streamlit apps are scripts that re-run top-to-bottom on every interaction. Understanding this execution model is the key to understanding everything else about Streamlit.

Part II: Short Answer (10 questions)

Q11. Write a minimal Streamlit app that loads a CSV, shows a DataFrame, and has a sidebar with a slider for the number of rows.

Answer
import streamlit as st
import pandas as pd

@st.cache_data
def load_data():
    return pd.read_csv("data.csv")

df = load_data()
n = st.sidebar.slider("Rows", 1, 100, 10)
st.dataframe(df.head(n))

Q12. Explain the difference between st.cache_data and st.cache_resource.

Answer`cache_data` caches serializable data (DataFrames, lists, dicts) and deep-copies the result to prevent mutation side effects. `cache_resource` caches non-serializable objects (database connections, ML models) by returning the same object reference, which is necessary for stateful objects. Use `cache_data` for data, `cache_resource` for resources.

Q13. Why should you avoid running a Streamlit app from Jupyter?

AnswerStreamlit apps require a command-line execution environment that Jupyter does not provide. The Streamlit process manages a web server, file watching, and page rendering — all of which conflict with Jupyter's own execution model. Always run Streamlit apps with `streamlit run app.py` from a terminal.

Q14. Write a st.form that collects a name, age, and submit button, then displays the values after submission.

Answer
with st.form("form"):
    name = st.text_input("Name")
    age = st.number_input("Age", 0, 120)
    submitted = st.form_submit_button("Submit")

if submitted:
    st.write(f"{name} is {age}")

Q15. What is st.rerun and when would you use it?

Answer`st.rerun()` forces an immediate re-run of the script. Useful when you want to programmatically trigger an update after some action — e.g., after writing to a database, clearing a cache, or updating session_state. Rare in practice; most re-runs are triggered automatically by widget interactions.

Q16. Describe the filter-transform-display pattern used in most Streamlit dashboards.

Answer(1) **Filter** widgets in the sidebar (or at the top of the main area). (2) **Transform**: apply the filters to the data, compute derived metrics. (3) **Display**: show the results as charts, metrics, and tables. The pattern is linear: top-to-bottom, filter → transform → display. Caching the data loading makes this pattern fast even for large datasets.

Q17. How do you create a multi-page Streamlit app?

AnswerCreate a `pages/` directory next to your main `app.py`. Each Python file in `pages/` becomes a page, with the filename (minus numeric prefix and extension) as the page label. For more control, use the `st.navigation` API in Streamlit 1.30+.

Q18. Write code to add a download button that exports a DataFrame as CSV.

Answer
st.download_button(
    "Download data",
    df.to_csv(index=False),
    file_name="data.csv",
    mime="text/csv",
)

Q19. Name three common Streamlit pitfalls and their fixes.

Answer(1) **Slow re-runs from uncached computation**: wrap expensive functions with `@st.cache_data` or `@st.cache_resource`. (2) **Widget key conflicts**: always provide unique `key` parameters for widgets that should have independent state. (3) **Mutating cached data**: treat cached data as immutable; make copies before modifying. (4) **Large data in session_state**: prefer caching over session_state for large DataFrames. (5) **Not pinning dependencies**: always specify versions in `requirements.txt`.

Q20. Explain why "apps are scripts" makes Streamlit different from traditional web frameworks.

AnswerTraditional frameworks like Flask use event-driven architecture: you write handlers that fire on specific events (button clicks, URL requests). Streamlit inverts this: the entire script runs top-to-bottom on every interaction, and widgets return values you use in a regular Python flow. The benefit is dramatically simpler code — no callbacks, no component lifecycle, no state management — at the cost of implicit dependencies and automatic re-execution of potentially expensive operations (which caching mitigates). The mental model is closer to a notebook than to a web app, and that is deliberate.

Scoring Rubric

Score Level Meaning
18–20 Mastery You can build production-ready Streamlit dashboards and know when to use Streamlit vs. alternatives.
14–17 Proficient You know the main APIs; review caching and session state.
10–13 Developing You grasp the basics; re-read Sections 29.4-29.8 and work all Part B exercises.
< 10 Review Re-read the full chapter.

After this quiz, continue to Chapter 30 (Dash), which introduces the main alternative dashboard framework.