A Beginners Guide To Streamlit - GeeksforGeeks

16 Dec, 2021
The trend of Data Science and Analytics is increasing day by day. From the data science pipeline, one of the most important steps is model deployment. We have a lot of options in python for deploying our model. Some popular frameworks are Flask and Django. But the issue with using these frameworks is that we should have some knowledge of HTML, CSS, and JavaScript. Keeping these prerequisites in mind, Adrien Treuille, Thiago Teixeira, and Amanda Kelly created “Streamlit”. Now using streamlit you can deploy any machine learning model and any python project with ease and without worrying about the frontend. Streamlit is very user-friendly.
In this article, we will learn some important functions of streamlit, create a python project, and deploy the project on a local web server.
Let’s install streamlit. Type the following command in the command prompt.
pip install streamlit
Once Streamlit is installed successfully, run the given python code and if you do not get an error, then streamlit is successfully installed and you can now work with streamlit.
Open command prompt or Anaconda shell and type
streamlit run filename.py
Run Streamlit file
Here my filename is ‘sample.py’. Open the local URL in the web browser.
1.  Title:
Python3
# import moduleimport streamlit as st # Titlest.title("Hello GeeksForGeeks !!!")
Output:
Title
2. Header and Subheader:
Python
# Headerst.header("This is a header") # Subheaderst.subheader("This is a subheader")
Output:
Header/Subheader
3. Text:
Python3
# Textst.text("Hello GeeksForGeeks!!!")
Output:
Text
4. Markdown:
Python3
# Markdownst.markdown("### This is a markdown")
Output:
Markdown
5.  Success, Info, Warning, Error, Exception:
Python3
# successst.success("Success") # successst.info("Information") # successst.warning("Warning") # successst.error("Error")
Output:
Success, Info, Warning and Error
6.  Write:
Using write function, we can also display code in coding format. This is not possible using st.text(”).
Python3
# Write textst.write("Text with write") # Writing python inbuilt function range()st.write(range(10))
Output:
write() function
7. Display Images:
Python3
# Display Images # import Image from pillow to open imagesfrom PIL import Imageimg = Image.open("streamlit.png") # display image using streamlit# width is used to set the width of an imagest.image(img, width=200)
Output:
Display image using streamlit
8. Checkbox:
A checkbox returns a boolean value. When the box is checked, it returns a True value else returns a False value.
Python3
# checkbox# check if the checkbox is checked# title of the checkbox is 'Show/Hide'if st.checkbox("Show/Hide"):     # display the text if the checkbox returns True value  st.text("Showing the widget")
Output:
Checkbox is not checked
The text is displayed when the box is checked
9. Radio Button:
Python3
# radio button# first argument is the title of the radio button# second argument is the options for the ratio buttonstatus = st.radio("Select Gender: ", ('Male', 'Female')) # conditional statement to print# Male if male is selected else print female# show the result using the success functionif (status == 'Male'):    st.success("Male")else:    st.success("Female")
Output:
Success shows Male when male option is selected
Success shows Female when Female option is selected
10. Selection Box:
You can select any one option from the select box.
Python3
# Selection box # first argument takes the titleof the selectionbox# second argument takes optionshobby = st.selectbox("Hobbies: ",                     ['Dancing', 'Reading', 'Sports']) # print the selected hobbyst.write("Your hobby is: ", hobby)
Output:
Selectbox showing options to select from
Selected option is printed
11. Multi-Selectbox:
The multi-select box returns the output in the form of a list. You can select multiple options.
Python3
# multi select box # first argument takes the box title# second argument takes the options to showhobbies = st.multiselect("Hobbies: ",                         ['Dancing', 'Reading', 'Sports']) # write the selected optionsst.write("You selected", len(hobbies), 'hobbies')
Output:
Multi-SelectBox
Selected 2 options
12. Button:
st.button() returns a boolean value. It returns a True value when clicked else returns False.
Python3
# Create a simple button that does nothingst.button("Click me for no reason") # Create a button, that when clicked, shows a textif(st.button("About")):    st.text("Welcome To GeeksForGeeks!!!")
Output:
Click the first button
Click the About button
13. Text Input:
Python3
# Text Input # save the input text in the variable 'name'# first argument shows the title of the text input box# second argument displays a default text inside the text input areaname = st.text_input("Enter Your name", "Type Here ...") # display the name when the submit button is clicked# .title() is used to get the input text stringif(st.button('Submit')):    result = name.title()    st.success(result)
Output:
Text Input
Display success message when the Submit button is clicked
14.  Slider:
Python3
# slider # first argument takes the title of the slider# second argument takes the starting of the slider# last argument takes the end numberlevel = st.slider("Select the level", 1, 5) # print the level# format() is used to print value# of a variable at a specific positionst.text('Selected: {}'.format(level))
Output:
Slider
Let us recollect everything that we learn above and create a BMI Calculator web app.
The formula of BMI Index when weight is in Kgs and height is in meters is:
Python3
# import the streamlit libraryimport streamlit as st # give a title to our appst.title('Welcome to BMI Calculator') # TAKE WEIGHT INPUT in kgsweight = st.number_input("Enter your weight (in kgs)") # TAKE HEIGHT INPUT# radio button to choose height formatstatus = st.radio('Select your height format: ',                  ('cms', 'meters', 'feet')) # compare status valueif(status == 'cms'):    # take height input in centimeters    height = st.number_input('Centimeters')         try:        bmi = weight / ((height/100)**2)    except:        st.text("Enter some value of height")         elif(status == 'meters'):    # take height input in meters    height = st.number_input('Meters')         try:        bmi = weight / (height ** 2)    except:        st.text("Enter some value of height")         else:    # take height input in feet    height = st.number_input('Feet')         # 1 meter = 3.28    try:        bmi = weight / (((height/3.28))**2)    except:        st.text("Enter some value of height") # check if the button is pressed or notif(st.button('Calculate BMI')):         # print the BMI INDEX    st.text("Your BMI Index is {}.".format(bmi))         # give the interpretation of BMI index    if(bmi < 16):        st.error("You are Extremely Underweight")    elif(bmi >= 16 and bmi < 18.5):        st.warning("You are Underweight")    elif(bmi >= 18.5 and bmi < 25):        st.success("Healthy")           elif(bmi >= 25 and bmi < 30):        st.warning("Overweight")    elif(bmi >= 30):        st.error("Extremely Overweight")
Output:
Calculate BMI Index, Scenario 1
Calculate BMI Index Scenario 2
Calculate BMI Index, Scenario 3
This way we can use streamlit to deploy our projects without having any knowledge of HTML, CSS, or JavaScript. 
Note: Streamlit is still under development and the team is bringing new concepts.
gabaa406
kashishsoda
gulshankumarar231
anikakapoor
Python Framework
Technical Scripter 2020
Machine Learning
Python
Technical Scripter
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
k-nearest neighbor algorithm in Python
Singular Value Decomposition (SVD)
Intuition of Adam Optimizer
ML | Logistic Regression using Python
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe