# Streamit

Streamlit is an open-source Python library that makes it easy to create and share beautiful, custom web apps for machine learning and data science projects. Unlike traditional web development frameworks, Streamlit is designed for simplicity and speed, so you don’t need to be a front-end expert to create interactive web applications.

Here’s a detailed and extensive tutorial on Streamlit.

---

## Table of Contents

1. **Installation**
    
2. **Hello World: Your First Streamlit App**
    
3. **Understanding the Basic Building Blocks**
    
    * `st.write()`
        
    * `st.title()`
        
    * `st.header()`
        
    * `st.text()`
        
    * `st.markdown()`
        
    * `st.latex()`
        
    * `st.code()`
        
4. **Adding Widgets**
    
    * Buttons: `st.button()`
        
    * Text Inputs: `st.text_input()`, `st.text_area()`
        
    * Sliders: `st.slider()`
        
    * Checkboxes: `st.checkbox()`
        
    * Selectboxes: `st.selectbox()`, `st.multiselect()`
        
    * Radio Buttons: [`st.radio`](http://st.radio)`()`
        
    * File Uploader: `st.file_uploader()`
        
5. **Displaying Data**
    
    * `st.dataframe()`
        
    * `st.table()`
        
    * `st.json()`
        
    * `st.metric()`
        
6. **Displaying Charts**
    
    * Line Chart: `st.line_chart()`
        
    * Bar Chart: [`st.bar`](http://st.bar)`_chart()`
        
    * Area Chart: `st.area_chart()`
        
    * Custom Matplotlib or Plotly charts
        
7. **Layout Customization**
    
    * `st.sidebar`
        
    * Columns: `st.columns()`
        
    * Expander: `st.expander()`
        
8. **Cashing for Performance Optimization**
    
9. **Handling Interactivity and Callbacks**
    
10. **Deploying Your Streamlit App**
    

---

### 1\. Installation

To install Streamlit, use pip. Run the following in your terminal or command prompt:

```bash
pip install streamlit
```

Once installed, you can verify the installation by running:

```bash
streamlit hello
```

This command will open up a demo app that showcases the capabilities of Streamlit.

---

### 2\. Hello World: Your First Streamlit App

Start by creating a new Python file. Let's call it [`app.py`](http://app.py). Open this file and add the following code:

```python
import streamlit as st

st.title("Hello, Streamlit!")
st.write("This is your first Streamlit app.")
```

To run the app, use the command:

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

This will start a local web server, and you can see your app in a browser window.

---

### 3\. Understanding the Basic Building Blocks

Streamlit provides a variety of functions to add text, titles, headers, and other elements. Let's go over the most common ones.

* `st.write()`: This is the most versatile function in Streamlit. It can display text, Pandas DataFrames, Matplotlib figures, etc.
    
    ```python
    st.write("Hello, Streamlit!")
    ```
    
* `st.title()`: Adds a large title to your app.
    
    ```python
    st.title("Streamlit App Title")
    ```
    
* `st.header()`: Adds a header to your app.
    
    ```python
    st.header("Section Header")
    ```
    
* `st.text()`: Displays raw text.
    
    ```python
    st.text("This is a plain text.")
    ```
    
* `st.markdown()`: Renders Markdown-formatted text.
    
    ```python
    st.markdown("## Markdown Example")
    ```
    
* `st.latex()`: Displays LaTeX formulas.
    
    ```python
    st.latex(r"\frac{1}{n}\sum_{i=1}^{n}x_i")
    ```
    
* `st.code()`: Displays code snippets with syntax highlighting.
    
    ```python
    st.code("print('Hello World!')", language='python')
    ```
    

---

### 4\. Adding Widgets

Widgets in Streamlit allow for user interaction. You can easily add buttons, text inputs, checkboxes, and other widgets.

* **Button**:
    
    ```python
    if st.button('Click Me'):
        st.write('Button clicked!')
    ```
    
* **Text Input**:
    
    ```python
    name = st.text_input('Enter your name:')
    if name:
        st.write(f'Hello, {name}!')
    ```
    
* **Text Area**:
    
    ```python
    description = st.text_area('Enter a description:')
    st.write(description)
    ```
    
* **Slider**:
    
    ```python
    age = st.slider('Select your age:', min_value=18, max_value=100)
    st.write(f'You are {age} years old.')
    ```
    
* **Checkbox**:
    
    ```python
    agree = st.checkbox('I agree')
    if agree:
        st.write('Agreed!')
    ```
    
* **Selectbox**:
    
    ```python
    option = st.selectbox('Choose a number:', [1, 2, 3, 4, 5])
    st.write(f'You selected {option}')
    ```
    
* **Multiselect**:
    
    ```python
    options = st.multiselect('Choose multiple numbers:', [1, 2, 3, 4, 5])
    st.write(f'You selected {options}')
    ```
    
* **Radio Buttons**:
    
    ```python
    status = st.radio('What is your status?', ('Active', 'Inactive'))
    if status == 'Active':
        st.write('You are active')
    else:
        st.write('You are inactive')
    ```
    
* **File Uploader**:
    
    ```python
    uploaded_file = st.file_uploader("Choose a file")
    if uploaded_file is not None:
        st.write('File uploaded:', uploaded_file.name)
    ```
    

---

### 5\. Displaying Data

Streamlit makes it easy to display tabular data. You can use it with Pandas DataFrames or any structured data.

* **DataFrame**:
    
    ```python
    import pandas as pd
    
    data = {
        'Column A': [1, 2, 3],
        'Column B': [10, 20, 30]
    }
    df = pd.DataFrame(data)
    st.dataframe(df)
    ```
    
* **Table**:
    
    ```python
    st.table(df)
    ```
    
* **JSON**:
    
    ```python
    st.json({'name': 'Streamlit', 'version': '1.0'})
    ```
    
* **Metric**:
    
    ```python
    st.metric(label="Temperature", value="70 °F", delta="1.2 °F")
    ```
    

---

### 6\. Displaying Charts

Streamlit provides built-in support for basic charts and works well with libraries like Matplotlib, Plotly, and Altair.

* **Line Chart**:
    
    ```python
    import numpy as np
    import pandas as pd
    
    chart_data = pd.DataFrame(
         np.random.randn(20, 3),
         columns=['a', 'b', 'c'])
    
    st.line_chart(chart_data)
    ```
    
* **Bar Chart**:
    
    ```python
    st.bar_chart(chart_data)
    ```
    
* **Area Chart**:
    
    ```python
    st.area_chart(chart_data)
    ```
    
* **Matplotlib Chart**:
    
    ```python
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    ax.plot([1, 2, 3, 4], [10, 20, 25, 30])
    st.pyplot(fig)
    ```
    
* **Plotly Chart**:
    
    ```python
    import plotly.express as px
    
    df = px.data.iris()
    fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
    st.plotly_chart(fig)
    ```
    

---

### 7\. Layout Customization

Streamlit offers various options to customize the layout of your app.

* **Sidebar**: You can place widgets in the sidebar to give your app a cleaner look.
    
    ```python
    st.sidebar.title("Sidebar")
    name = st.sidebar.text_input("Enter your name:")
    st.sidebar.write(f"Hello {name}")
    ```
    
* **Columns**: You can create a multi-column layout for better organization.
    
    ```python
    col1, col2 = st.columns(2)
    
    with col1:
        st.write("This is column 1")
    with col2:
        st.write("This is column 2")
    ```
    
* **Expander**: You can hide content under an expander that users can click to reveal.
    
    ```python
    with st.expander("See more"):
        st.write("Hidden content goes here!")
    ```
    

---

### 8\. Caching for Performance Optimization

Streamlit provides a simple caching mechanism to speed up your apps by storing the results of expensive computations.

```python
@st.cache
def expensive_function():
    # simulate a time-consuming operation
    import time
    time.sleep(5)
    return "Expensive result"

result = expensive_function()
st.write(result)
```

---

### 9\. Handling Interactivity and Callbacks

Streamlit automatically reruns the script from the top every time a widget's state changes. This keeps the app simple but may lead to unnecessary re-computations. You can control some interactivity via the `on_change` parameter for widgets.

For example:

```python
def update():
   

 st.write("The slider value changed!")

st.slider('Move me', min_value=0, max_value=100, on_change=update)
```

---

### 10\. Deploying Your Streamlit App

Streamlit Cloud offers free hosting for your apps. You can deploy by connecting your GitHub repository to Streamlit Cloud.

1. Create a GitHub repository and push your code.
    
2. Visit [Streamlit Cloud](https://share.streamlit.io/) and sign in.
    
3. Follow the steps to connect your GitHub repository.
    
4. Your app will be live and shareable with a URL like [`https://your-app-name.streamlit.app`](https://your-app-name.streamlit.app).
    

---

### Conclusion

Streamlit is a powerful tool that allows you to build interactive web applications quickly without needing extensive web development experience. With its simple API and wide support for charts, dataframes, and interactivity, it’s ideal for creating machine learning and data science dashboards.0
