# How to Build Your First Streamlit App in Python

> A Streamlit tutorial for beginners: install Streamlit, write app.py with widgets, st.metric, st.line_chart and a table, understand reruns, and lay out the page with a sidebar, columns and tabs.

Source: https://www.pythoncharts.com/streamlit/first-streamlit-app/ | Published: 2026-11-26 | Author: Alex Scott | Category: Streamlit | Tags: streamlit, st.metric, st.line_chart, st.sidebar, dashboard

To build a Streamlit app, write an ordinary Python script that calls functions like `st.title`, `st.slider`, and `st.line_chart`, then start it with `streamlit run app.py`. Streamlit serves it as a web page and reruns the script whenever someone changes a widget, so there is no HTML, JavaScript, or callback wiring to write. The code here was tested with Streamlit 1.67.

## Quick Example

Install Streamlit with pip (or `uv add streamlit` in a uv project):

```bash
pip install streamlit
```

Save this as `app.py`. It's a small running log with 12 weeks of simulated distances for three runners.

```python
import numpy as np
import pandas as pd
import streamlit as st

rng = np.random.default_rng(21)
weeks = pd.date_range("2026-06-01", periods=12, freq="W-MON")
runs = pd.DataFrame({
    "week": weeks,
    "Priya": (18 + 1.4 * np.arange(12) + rng.normal(0, 2.0, 12)).round(1),
    "Marcus": (30 + 0.3 * np.arange(12) + rng.normal(0, 3.0, 12)).round(1),
    "Lena": (12 + 1.1 * np.arange(12) + rng.normal(0, 1.5, 12)).round(1),
})
colors = {"Priya": "#e8590c", "Marcus": "#1971c2", "Lena": "#2f9e44"}

st.title("Running Log")

runner = st.selectbox("Runner", list(colors))
goal = st.slider("Weekly goal (km)", 10, 50, 28)

distance = runs[runner]
left, middle, right = st.columns(3)
left.metric("Last week", f"{distance.iloc[-1]:.1f} km",
            f"{distance.iloc[-1] - distance.iloc[-2]:+.1f} km")
middle.metric("12-week total", f"{distance.sum():.0f} km")
right.metric("Weeks at goal", f"{(distance >= goal).sum()} of 12")

chart_data = runs[["week", runner]].assign(Goal=goal)
st.line_chart(chart_data, x="week", y=[runner, "Goal"],
              color=[colors[runner], "#adb5bd"],
              x_label="Week", y_label="Distance (km)")
```

Then run it:

```bash
streamlit run app.py
```

Your browser opens at `http://localhost:8501`.

![Streamlit app titled Running Log with a runner dropdown, a weekly goal slider, three metrics, and a line chart of Priya's weekly distance rising across a grey goal line at 28 km](https://www.pythoncharts.com/streamlit/first-streamlit-app/images/first-streamlit-app.png)

Pick a different runner or drag the goal slider and the metrics and chart update. With the default goal of 28 km, Priya hit it in 4 of the 12 weeks.

## How Does a Streamlit App Run?

Streamlit runs your script from top to bottom, and each `st.` call adds an element to the page in order. When someone moves a widget, the whole script runs again and the widget returns its new value.

That's why the example has no event handlers. `goal = st.slider(...)` is a plain variable, and the code below it uses whatever value it has on this run.

Two consequences are worth knowing early:

- **Local variables reset on every run.** To remember something between runs, such as a running total or a list of entries, use `st.session_state`.
- **Slow code runs again every time.** Wrap data loading in `@st.cache_data` so it only runs when its inputs change.

While you edit, Streamlit notices the saved file and offers **Rerun** and **Always rerun** buttons in the top corner. Choose "Always rerun" and the page refreshes each time you save. To start with that behavior, use `streamlit run app.py --server.runOnSave true`.

## Widgets: Getting Input From the User

Every widget takes a label and returns the current value. These cover most apps:

| Widget | Returns |
|---|---|
| `st.slider("Goal", 10, 50, 28)` | A number (or a tuple for a range slider) |
| `st.selectbox("Runner", names)` | One option |
| `st.multiselect("Runners", names, default=names)` | A list of options |
| `st.checkbox("Show table")` | `True` or `False` |
| `st.date_input("Start", date(2026, 6, 1))` | A `datetime.date` |
| `st.number_input("Distance", 0.0, 100.0, 5.0)` | A number |
| `st.text_input("Name")` | A string |
| `st.button("Save")` | `True` only on the run triggered by the click |
| `st.file_uploader("CSV", type="csv")` | A file-like object, or `None` |

`st.button` is the one that surprises people. It returns `True` for a single run, then goes back to `False` as soon as any other widget changes.

## Add a Sidebar, Tabs, and a Table

Put controls in `st.sidebar` to keep them away from the content, and use `st.tabs` to stack views in the same space. This second version of `app.py` compares several runners at once:

```python
import numpy as np
import pandas as pd
import streamlit as st

st.set_page_config(page_title="Running Log", layout="wide")

rng = np.random.default_rng(21)
weeks = pd.date_range("2026-06-01", periods=12, freq="W-MON")
runs = pd.DataFrame({
    "week": weeks,
    "Priya": (18 + 1.4 * np.arange(12) + rng.normal(0, 2.0, 12)).round(1),
    "Marcus": (30 + 0.3 * np.arange(12) + rng.normal(0, 3.0, 12)).round(1),
    "Lena": (12 + 1.1 * np.arange(12) + rng.normal(0, 1.5, 12)).round(1),
})
colors = {"Priya": "#e8590c", "Marcus": "#1971c2", "Lena": "#2f9e44"}

with st.sidebar:
    st.header("Filters")
    selected = st.multiselect("Runners", list(colors), default=list(colors))
    n_weeks = st.slider("Weeks to show", 4, 12, 12)

st.title("Running Log")

if not selected:
    st.info("Pick at least one runner in the sidebar.")
    st.stop()

recent = runs.tail(n_weeks)
trend, totals, table = st.tabs(["Trend", "Totals", "Data"])

with trend:
    st.line_chart(recent, x="week", y=selected,
                  color=[colors[r] for r in selected],
                  x_label="Week", y_label="Distance (km)")

with totals:
    summary = recent[selected].sum().rename_axis("runner").reset_index(name="km")
    st.bar_chart(summary, x="runner", y="km", horizontal=True,
                 sort="-km", y_label="", x_label="Total distance (km)")

with table:
    st.dataframe(recent, hide_index=True,
                 column_config={"week": st.column_config.DateColumn("Week of")})
    st.download_button("Download CSV", recent.to_csv(index=False),
                       file_name="runs.csv", mime="text/csv")
```

![Streamlit app with a sidebar holding a runner multiselect and a weeks slider, and tabs above a line chart of weekly distance for Priya, Marcus and Lena](https://www.pythoncharts.com/streamlit/first-streamlit-app/images/first-streamlit-app-sidebar.png)

What changed:

- `st.set_page_config(layout="wide")` uses the full browser width instead of a centered column.
- Anything inside `with st.sidebar:` goes in the collapsible left panel.
- `st.stop()` ends the run early, which is a clean way to handle empty input before the charts try to draw nothing.
- All three tabs are computed on every run. Tabs only control what's visible.

## Which Chart Function Should You Use?

`st.line_chart`, `st.bar_chart`, `st.area_chart`, and `st.scatter_chart` draw straight from a DataFrame. When you need annotations, dual axes, or another chart type, build the figure in a plotting library and pass it to `st.pyplot`, `st.plotly_chart`, or `st.altair_chart`. The [Streamlit chart comparison](https://www.pythoncharts.com/streamlit/streamlit-charts-compared/) shows the same chart all four ways.

## Troubleshooting

- **`streamlit: command not found`**: the install location isn't on your `PATH`, or you installed into a different environment. Run `python -m streamlit run app.py`, or `uv run streamlit run app.py` in a uv project.
- **Nothing happens with `python app.py`**: that runs the script without a server and only prints warnings. Use `streamlit run`.
- **Port 8501 is busy**: Streamlit picks the next free port. To choose one yourself, add `--server.port 8600`.
- **`StreamlitDuplicateElementId`**: two identical widgets need distinct `key=` values.

## Similar Topics

- [Streamlit Tutorials: A Guide from First App to Deployment](https://www.pythoncharts.com/streamlit/streamlit-python-guide/)
- [Charts in Streamlit: st.line_chart vs Matplotlib vs Plotly vs Altair](https://www.pythoncharts.com/streamlit/streamlit-charts-compared/)
- [Python Interactive Charting Libraries Compared](https://www.pythoncharts.com/python/python-interactive-charting-libraries-compared/)
