Streamlit - A Beginner's Walkthrough

I recently got started with Streamlit, and I wanted to jot down everything I learned in one place. So if you're new to Python web apps or just want to build something quick and interactive, this post will walk you through basic Streamlit concepts with code, explanations, and a few interactive widgets.
What is Streamlit?
Streamlit is an open-source framework that helps you build beautiful, interactive web apps for your machine learning and data projects - all in Python.
Installation is super simple:
pip install streamlit
To launch streamlit app in the browser:
streamlit run filename.py
Streamlit UI Elements
st.title()
Displays a prominent title at the top of the app.
import streamlit as st
st.title("Hello Streamlit")
st.subheader()
Displays a medium-sized subheading below the main title, useful for section titles.
st.subheader('Subheading')
st.write()
Displays text, numbers, DataFrames, charts, or any other object directly on the app.
import pandas as pd
# Display a simple text
st.write("This is a simple text")
# Create a simple dataframe
df = pd.DataFrame({
'first column':[1,2,3,4],
'second column':[10,20,30,40]
})
# Display the dataframe
st.write("Here is the dataframe")
st.write(df)
st.code()
Displays formatted code blocks in the app.
st.code('import streamlit as st\nimport numpy as np')
st.error()
Displays an error message in red. It is useful for validations or exceptions.
st.error("Something went wrong!")
st.success()
Displays a green success message. It is useful for confirming actions like training completion or form submission.
st.success("Model trained successfully!")
st.line_chart()
Displays a line chart using a DataFrame or NumPy array. It automatically plots each column as a separate line.
import pandas as pd
import numpy as np
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['a', 'b', 'c']
)
st.line_chart(chart_data)
Streamlit Widgets/Input Elements
st.text_input()
Displays a textbox where users can type input. Returns the input as a string.
name = st.text_input("Enter your name")
if name:
st.write(f"Hello {name}")
st.slider()
Displays a slider widget for selecting a numeric value within a given range. Returns the selected number.
age = st.slider("Select your age:", 0, 100, 25)
st.write(f"Your age is {age}")
st.selectbox()
Displays a dropdown menu for selecting a single option from a list. Returns the selected item.
options = ['Python', 'Java', 'C', 'C++']
choice = st.selectbox("Choose your favourite language", options)
st.write(f"You selected {choice}")
st.file_uploader()
Displays a file upload button. Allows users to upload a file, and returns a file-like object.
# creating a file
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df.to_csv('sample.csv')
#upload file
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
if uploaded_file is not None:
df = pd.read_csv(uploaded_file)
st.write(df)
Project - Build an Iris Flower Classifier with Streamlit
Now, let’s put everything together and build a complete ML web app using Streamlit and Scikit-learn.
We’ll use the classic Iris dataset, train a model using RandomForestClassifier, and then let the user input flower measurements via interactive sliders to predict the species.
Step 1: Import Required Libraries
Load all necessary libraries for building the app like Streamlit for UI, pandas for data handling, and Scikit-learn for loading the dataset and building the model.
import streamlit as st
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
Step 2: Load and Cache the Dataset
Create a function to load the Iris dataset using Scikit-learn and convert it to a pandas DataFrame. Cache the function using @st.cache_data
so it doesn’t reload every time the app runs.
@st.cache_data
def load_data():
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['species'] = iris.target
return df, iris.target_names
df, target_names = load_data()
Step 3: Preview the Dataset
Display the first few rows of the dataset and the target class labels to get a quick look at the data.
st.subheader('Iris Dataset Preview')
st.write(df.head())
st.write(target_names)
Step 4: Train the Random Forest Model
Train a RandomForestClassifier
using the feature columns of the dataset and show a success message once the model is trained.
model = RandomForestClassifier()
model.fit(df.iloc[:, :-1], df['species'])
st.success("Model Trained Successfully")
Step 5: Add Sliders in the Sidebar for Input
Add sliders in the sidebar to let users choose sepal and petal measurements for a flower. These inputs will be used to make predictions.
st.sidebar.header('Set Iris Flower Measurements')
sepal_length = st.sidebar.slider('Sepal Length (cm)', float(df['sepal length (cm)'].min()), float(df['sepal length (cm)'].max()))
sepal_width = st.sidebar.slider('Sepal Width (cm)', float(df['sepal width (cm)'].min()), float(df['sepal width (cm)'].max()))
petal_length = st.sidebar.slider("Petal Length (cm)", float(df['petal length (cm)'].min()), float(df['petal length (cm)'].max()))
petal_width = st.sidebar.slider("Petal Width (cm)", float(df['petal width (cm)'].min()), float(df['petal width (cm)'].max()))
Step 6: Make Predictions from User Input
Use the selected measurements to create an input sample, make a prediction with the model, and also get the prediction probabilities.
input_data = [[sepal_length, sepal_width, petal_length, petal_width]]
prediction = model.predict(input_data)
prediction_proba = model.predict_proba(input_data)
prediction_species = target_names[prediction[0]]
Step 7: Display the Prediction Result
Show the predicted species clearly so the user knows what type of flower matches the input.
st.subheader('Prediction Result')
st.write(f'**Predicted Species:** {prediction_species}')
Step 8: Show the Prediction Probabilities
Display a bar chart to visualize the model’s confidence for each of the possible species.
st.subheader("Prediction Probabilities")
proba_df = pd.DataFrame(prediction_proba, columns=target_names)
st.bar_chart(proba_df.T)
Here's what the final app looks like in action -
Summary
Streamlit is one of the easiest and most effective tools to turn your Python projects into interactive web apps, with many more components available at streamlit.io/components.
Subscribe to my newsletter
Read articles from Suraj Rao directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Suraj Rao
Suraj Rao
Hi, I'm Suraj I'm an aspiring AI/ML engineer passionate about building intelligent systems that learn, see, and adapt to the real world.