In this guide, we'll walk through the process of building a basic calculator application using Python and Streamlit. Streamlit is a powerful library for building interactive web applications with minimal code. Let's get started!
-
Make sure you have Python installed on your system. You can download it from python.org.
-
Install Streamlit using pip:
pip install streamlit
alternative: streamlit sandbox
-
Create a new directory for your project:
mkdir simple-calculator cd simple-calculator
-
Inside the project directory, create a new Python script for the calculator application. Let's name it calculator.py.
-
Open
calculator.py
in your favorite text editor or IDE. -
Import the necessary libraries:
import streamlit as st
-
Define the Streamlit app layout:
st.title('Simple Calculator')
-
Add input fields for numbers and operators:
num1 = st.number_input('Enter the first number:') operator = st.selectbox('Select operator:', ['+', '-']) num2 = st.number_input('Enter the second number:')
-
Add a button to perform the calculation:
if st.button('Calculate'): result = None if operator == '+': result = num1 + num2 elif operator == '-': result = num1 - num2 st.write(f'Result: {result}')
-
Save your changes to
calculator.py
. -
Open your terminal and navigate to the project directory (simple-calculator).
-
Run the Streamlit application:
streamlit run calculator.py
- Once the application is running, open your web browser and navigate to the provided URL (usually http://localhost:8501).
-
Task 1: Multiplication: Implement the multiplication functionality by adding a conditional block for the
*
operator. -
Task 2: Division: Implement the division functionality by adding a conditional block for the
/
operator. Make sure to handle division by zero error.
-
Use the input fields and buttons to perform calculations. Enter numbers and select operators to build your expression, and click the "Calculate" button to see the result.
-
Test different scenarios to ensure the calculator behaves as expected.
-
Feel free to customize the layout and styling of the calculator application using Streamlit's features.
-
You can add more advanced features or functionalities to the calculator based on your requirements and preferences.
-
Explore Streamlit's documentation for more ideas and possibilities.
Congratulations! You've successfully built a simple calculator application using Python and Streamlit.