Streamlit Tutorial for Beginners: Build Data Science Apps in Python
On this page
Streamlit is an open-source Python library that turns data scripts into interactive web apps without HTML, CSS or JavaScript. You write ordinary Python, add widgets such as sliders, file uploaders and buttons, and Streamlit renders them in the browser. For data science students, it is the quickest way to turn a notebook analysis or a machine learning model into something a recruiter or manager can actually click and use.
In this tutorial you will install Streamlit, learn the one idea that makes it work, use the most important widgets, and build two small projects: a CSV sales dashboard and an ML prediction app. Both examples were tested on Streamlit 1.66.
Install and run your first app
Create a virtual environment, then install Streamlit and pandas:
pip install streamlit pandas
Create a file called app.py:
import streamlit as st
st.title("Hello, Streamlit")
name = st.text_input("Your name")
if name:
st.write(f"Welcome, {name}!")
Run it from the terminal:
streamlit run app.py
Your browser opens at http://localhost:8501. Edit the file and save; Streamlit offers to rerun the app with your changes.
The one idea to understand: the script reruns
Every time a user interacts with a widget, Streamlit reruns your whole script from top to bottom, with the widget holding its new value. That is why the code above can simply read name and use it. This model keeps apps easy to write, but it has two consequences:
- Slow steps, such as loading a large CSV or a model, would repeat on every click, so you cache them.
- Ordinary variables reset on every rerun. To remember values (a counter, a chat history), use
st.session_state.
The widgets and layout you will use most
| Need | Streamlit function |
|---|---|
| Titles and text | st.title, st.header, st.write, st.markdown |
| User input | st.text_input, st.number_input, st.slider, st.selectbox, st.multiselect, st.checkbox, st.button |
| Files | st.file_uploader, st.download_button |
| Data display | st.dataframe, st.table, st.metric |
| Charts | st.line_chart, st.bar_chart, st.plotly_chart, st.pyplot |
| Layout | st.sidebar, st.columns, st.tabs, st.expander |
| Messages | st.info, st.success, st.warning, st.error |
| Caching | @st.cache_data, @st.cache_resource |
Caching: cache_data vs cache_resource
- @st.cache_data is for functions that return data, such as a DataFrame from a CSV, a database query or an API call. Streamlit stores the result and returns a copy on later runs.
- @st.cache_resource is for objects you want to create once and share, such as a trained ML model, a database connection or an LLM client.
Project 1: a CSV sales dashboard
This app lets a user upload a sales CSV (columns: date, region, product, amount), filter by region in the sidebar, and see KPIs, a chart and the data.
import pandas as pd
import streamlit as st
st.set_page_config(page_title="Sales Explorer", layout="wide")
st.title("Sales Explorer")
uploaded = st.file_uploader("Upload a sales CSV", type="csv")
@st.cache_data
def load(file):
return pd.read_csv(file)
if uploaded is None:
st.info("Upload a CSV with columns: date, region, product, amount")
st.stop()
df = load(uploaded)
regions = st.sidebar.multiselect("Region", sorted(df["region"].unique()), default=sorted(df["region"].unique()))
filtered = df[df["region"].isin(regions)]
col1, col2 = st.columns(2)
col1.metric("Total sales", f"{filtered['amount'].sum():,.0f}")
col2.metric("Orders", len(filtered))
st.bar_chart(filtered.groupby("product")["amount"].sum())
st.dataframe(filtered, width="stretch")
st.stop() ends the run until a file is uploaded, so the rest of the code never sees an empty input. Note width="stretch": older tutorials use use_container_width=True, which current Streamlit versions flag as deprecated.
Project 2: a machine learning prediction app
Train a model in your notebook, save it with joblib.dump(model, "iris_model.joblib"), then serve it:
import joblib
import streamlit as st
@st.cache_resource
def load_model():
return joblib.load("iris_model.joblib")
model = load_model()
species = ["setosa", "versicolor", "virginica"]
st.title("Iris Flower Predictor")
sl = st.slider("Sepal length (cm)", 4.0, 8.0, 5.8)
sw = st.slider("Sepal width (cm)", 2.0, 4.5, 3.0)
pl = st.slider("Petal length (cm)", 1.0, 7.0, 4.3)
pw = st.slider("Petal width (cm)", 0.1, 2.5, 1.3)
if st.button("Predict"):
pred = model.predict([[sl, sw, pl, pw]])[0]
st.success(f"Predicted species: {species[pred]}")
With the default slider values and a random forest trained on the Iris dataset, the app predicts versicolor. Replace the Iris model with your own project (house prices, loan approval, churn) and you have a portfolio demo. If you need other systems to call your model, expose it as an API instead with FastAPI.
Deploying your Streamlit app
- Streamlit Community Cloud: push your app and a
requirements.txtto a public GitHub repository and deploy it from share.streamlit.io. Good for portfolio projects. - Docker: package the app and run it on any server or cloud service; see Docker for machine learning.
- Cloud platforms such as AWS, Azure or GCP for company projects that need authentication and private data.
Never commit API keys or passwords to GitHub. Use Streamlit’s secrets.toml or environment variables.
Streamlit vs Power BI vs Flask
| Tool | Best for | Skill needed |
|---|---|---|
| Streamlit | Data and ML apps, prototypes, internal tools, LLM demos | Python |
| Power BI | Business dashboards and self-service reporting for managers | Power Query, DAX, data modelling |
| Flask / FastAPI | Full web applications and APIs with custom front ends | Python plus web development |
Frequently asked questions
Is Streamlit free?
Yes. Streamlit is open source under the Apache 2.0 licence, and Community Cloud has a free tier for public apps.
Can I build a chatbot with Streamlit?
Yes. Streamlit has chat elements (st.chat_input and st.chat_message) and is widely used for RAG and LLM demos. Store the conversation in st.session_state so it survives reruns.
Is Streamlit good for production?
It is excellent for internal tools, prototypes and demos. For high-traffic public products with complex user flows, teams usually build a dedicated front end and API.
Do I need to know HTML or JavaScript?
No. Everything in this tutorial is pure Python. You can add custom styling or components later if you need them.
Related reading
- Python projects for beginners
- FastAPI for machine learning
- Docker for machine learning
- Data cleaning in Python
- Generative AI projects
Want to build and deploy portfolio apps like these with guidance? See our Python course and Data Science course.
A note from Mehul Prajapati
I have spent 18+ years in IT and training and have personally mentored 12,000+ students. If you are planning your next step in Python and data science projects and want a second opinion on your learning path, I am happy to help.
“The technology you learn today may change tomorrow, but your ability to learn will always be your biggest strength. Stay curious, keep upgrading yourself, and never stop growing.”
Message me on WhatsApp at +91 99301 12627 and tell me which blog you read. I would love to hear from you.
Learn with Mehul Prajapati in Borivali West
At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support and placement assistance on the Python course. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.
Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072
Visit the centre or call us to choose the right course and batch and to know the current fee structure.