New to Rust? Grab our free Rust for Beginners eBook Get it free →
Building Calculator with Streamlit

For a small interactive calculator, a Python project can keep its inputs and arithmetic in one app file. Streamlit runs a Python script as an interactive web app.
I’ll show how to build and launch the calculator, then explain how its inputs behave when the app reruns.
TL;DR
This Python-based calculator demonstrates a four-operation Streamlit interface. I tested its operation branches and division guard with AppTest.
- Use st.number_input() for operands and st.selectbox() for the operation.
- Handle division by zero before dividing.
- Start the app with streamlit run calculator_app.py.
What Is a Streamlit Calculator?
Streamlit is a Python framework that runs a script as an interactive web app. I keep this example to separate numeric fields and a fixed operation menu, which keeps its inputs and calculations explicit.
A text box containing 2+3*4 needs a parser to decide operator precedence and reject malformed input.
The site’s beginner’s guide to Streamlit in Python introduces the framework. The Streamlit data visualization guide is a next step when an app needs charts rather than a single result.
How to Build a Calculator with Streamlit
Put the widgets and operation logic in one Python file, then let Streamlit run that file as an app. I used an isolated workspace virtual environment with Streamlit 1.66.1. The complete example appears below.
Step 1: Create the app file
Save the code as calculator_app.py. The page setup and title below give the app a browser title and a clear heading.
import streamlit as st
st.set_page_config(page_title="Simple Calculator", page_icon="🧮", layout="centered")
st.title("Simple Calculator")
st.write("Enter two numbers, choose an operation, then calculate.")
st.set_page_config() controls page-level presentation. Calling it before the title keeps the page setup at the start of the script, where it is clear which settings belong to the whole app.
Step 2: Add number inputs
Use st.number_input() twice to collect the calculator’s operands.
left, right = st.columns(2)
with left:
first = st.number_input("First number", value=0.0, key="first")
with right:
second = st.number_input("Second number", value=0.0, key="second")
Division can produce fractional results, which is why these widgets use floating-point defaults. Streamlit’s number input uses a 0.01 step for floats and 1 for integers, and the widget keys keep each operand associated with its field across reruns.
The example leaves bounds open because its operations have no domain-specific limits.
Step 3: Add the operator selector
The selector returns the chosen option as a value. Use the same option text in the corresponding conditional branch.
operation = st.selectbox(
"Operation",
["Add (+)", "Subtract (−)", "Multiply (×)", "Divide (÷)"],
)
By default, the first item is selected on the initial render, so this app starts with addition.
Step 4: Calculate and display the result
Use the Calculate button as the submission action for one operation.
if st.button("Calculate", type="primary"):
if operation == "Add (+)":
result = first + second
elif operation == "Subtract (−)":
result = first - second
elif operation == "Multiply (×)":
result = first * second
elif second == 0:
st.error("Cannot divide by zero. Change the second number and try again.")
st.stop()
else:
result = first / second
st.success(f"Result: {result:g}")
The guard runs before division, so a zero second operand produces a message instead of a traceback. The selected branch computes one result and displays it with general numeric formatting.
Operand order matters for subtraction and division: the app calculates first minus second and first divided by second.
import streamlit as st
st.set_page_config(page_title="Simple Calculator", page_icon="🧮", layout="centered")
st.title("Simple Calculator")
st.write("Enter two numbers, choose an operation, then calculate.")
left, right = st.columns(2)
with left:
first = st.number_input("First number", value=0.0, key="first")
with right:
second = st.number_input("Second number", value=0.0, key="second")
operation = st.selectbox("Operation", ["Add (+)", "Subtract (−)", "Multiply (×)", "Divide (÷)"])
if st.button("Calculate", type="primary"):
if operation == "Add (+)":
result = first + second
elif operation == "Subtract (−)":
result = first - second
elif operation == "Multiply (×)":
result = first * second
elif second == 0:
st.error("Cannot divide by zero. Change the second number and try again.")
st.stop()
else:
result = first / second
st.success(f"Result: {result:g}")
Run this block as python3 calculator_app.py after saving it under that file name. Then use the Streamlit command below to serve the app.
Step 5: Run the Streamlit app
Use the venv’s Python to install Streamlit. Start the app with the same environment’s command.
python3 -m venv .venv .venv/bin/python -m pip install streamlit
From the directory containing calculator_app.py, run the Streamlit command below. It starts a local server and prints a browser address.
./.venv/bin/streamlit run calculator_app.py --server.address 127.0.0.1
I ran the command in this workspace and recorded its startup lines below. The server prints a loopback URL for access from its host machine.
Collecting usage statistics. To deactivate, set browser.gatherUsageStats to false. You can now view your Streamlit app in your browser. URL: http://127.0.0.1:8501 2026-10-25 22:11:43.518 Uvicorn server started on 127.0.0.1:8501 [command timed out]

Open the printed address on the machine running Streamlit.
To try a calculation, enter 18 and 6, select division, and click Calculate. The result should be 3. Change the operation or either input and click again to run the calculation with the new values.
Handle Division by Zero and Reruns
I use the table to choose how reruns and numeric inputs should affect the next step in this example.
| Case | What happens | What to do |
|---|---|---|
| Divide by zero | Python raises ZeroDivisionError if division is attempted. | Check the second operand and show an error before dividing. |
| Change an input after calculating | Streamlit reruns the script. The button is false on that run. | Click Calculate again, or store a prior result in session state if it must persist. |
| Decimal arithmetic | Binary floating-point can show representation differences. | Set a clear display and rounding policy. Python’s decimal module provides decimal arithmetic for money-related calculations. |
| Very large integers | Streamlit documents serialization precision limits for integer widget values above 2^53−1 in magnitude in its number input reference. | Do not use this widget as an arbitrary-precision calculator. |
An st.form can wait to send the operands and operation until submission, while Session State carries values across reruns in the browser session.
A swapped operand or unintended decimal can change the result. Check both inputs and the selected operation against the labels.
How to Add More Calculator Functions
Choose each new function by defining its inputs and deciding which values the app should retain.
- Percentage: define whether the user means a percentage of a value or a percentage change.
- Exponents and roots: set the allowed exponent and decide how to handle a negative input for a square root.
- Memory: decide how a user stores, recalls, changes and clears the remembered value.
- History: decide which calculations the app should retain and whether they survive a closed browser session.
A memory register holds one value for later use. History stores a sequence, so decide whether it includes operands, results or both.
For example, a move from 20 to 25 is an increase of 5, which is 25 percent of the original value. If that original value is zero, the percentage change is undefined because the formula divides by zero. Give that input its own message.
A scientific calculator adds functions such as trigonometry and logarithms. These also need a choice between degrees and radians, as well as defined handling for values outside a function’s domain.
A Streamlit session state value lasts for the browser session, while a saved history needs persistent storage. Keep these as separate design decisions.
For a square-root function, choose how the app responds to a negative input before adding the widget. A clear error keeps the interaction consistent with the division guard, while a complex-number result would require a different display and explanation.
Common Calculator Errors and Next Steps
Common problems come from the environment, widget values, or Streamlit reruns. Use the symptom to locate the relevant environment or widget check.
| Symptom | Likely cause | Check or fix |
|---|---|---|
| streamlit: command not found | The shell is using an environment without Streamlit, or the executable directory is absent from PATH. | Run the environment’s executable directly with ./.venv/bin/streamlit run calculator_app.py. |
| ModuleNotFoundError for streamlit | The selected Python interpreter and the installation environment differ. | Use ./.venv/bin/python -m streamlit run calculator_app.py from the project directory. |
| Address already in use | Another process is listening on the selected port. | Stop the app instance you started, or choose an unused port with --server.port. |
| Page opens but edits reset a value | Each widget change reruns the script. Keep a calculated answer in session state when it should remain visible after another widget change. | Give the widget a consistent key, then store the calculated answer in session state if it should remain visible after another change. |
| Decimal display differences | Binary floating-point cannot represent every decimal fraction exactly. | Choose display rounding, or use decimal.Decimal when decimal arithmetic is required. |
Keep the launch command in the same directory as calculator_app.py so relative paths and the virtual environment resolve as shown. This lets the command find both the app file and its installed Streamlit executable.
For a single-user learning example, the local server is enough to test the widget flow. Before sharing a deployed app, review its inputs, data handling, and access settings for the environment where it will run.
- Confirm the interpreter and package belong to the same virtual environment.
- Try addition, subtraction, multiplication, division, and a zero divisor.
- Choose whether a result persists after an input change.
A percentage operation needs a precise definition. Those choices determine the labels, state and tests the interface needs.
Conclusion
Use the official widget references below for return values and limits when adapting the sample to another Streamlit version.
For the widget behavior, consult Streamlit’s number input, select box and button references. The official run your app guide covers the command used here.
FAQ
These answers cover the implementation choices that tend to come up when adapting the example.
How do I run a Streamlit calculator?
Save the app as calculator_app.py, open a terminal in that directory, and activate the environment where Streamlit is installed. Run streamlit run calculator_app.py, then open the local address Streamlit prints.
How should the app handle division by zero?
Check whether the second operand is zero before performing division. Show a user-facing error and stop that calculation rather than allowing ZeroDivisionError to interrupt the app.
Why does the result disappear after I change an input?
Streamlit reruns the script after widget changes, and a button is true only on the run triggered by its click. Click Calculate again, or store the result in session state if it must persist.




