Waqas0327's picture
Update app.py
6278bc0 verified
import streamlit as st
import math
st.set_page_config(
page_title="Advanced Calculator",
layout="centered",
page_icon="๐Ÿงฎ"
)
st.title("๐Ÿงฎ Advanced Calculator")
# Initialize history if not already present
if 'history' not in st.session_state:
st.session_state.history = []
# Layout inputs side by side
col1, col2 = st.columns(2)
with col1:
num1 = st.number_input("First Number", format="%.4f", key="num1")
with col2:
num2 = st.number_input("Second Number", format="%.4f", key="num2")
# Operation selection
operation = st.selectbox("Select Operation", [
"โž• Addition",
"โž– Subtraction",
"โœ–๏ธ Multiplication",
"โž— Division",
"๐ŸŸฐ Power (num1^num2)",
"โˆš Square Root of First Number",
"% Percentage (num1% of num2)",
"1/x Reciprocal of First Number"
])
# Result calculation
result = None
symbol = ""
error = None
if st.button("๐Ÿ”ข Calculate"):
try:
if operation == "โž• Addition":
result = num1 + num2
symbol = "+"
elif operation == "โž– Subtraction":
result = num1 - num2
symbol = "-"
elif operation == "โœ–๏ธ Multiplication":
result = num1 * num2
symbol = "*"
elif operation == "โž— Division":
if num2 != 0:
result = num1 / num2
symbol = "/"
else:
error = "Division by zero is not allowed."
elif operation == "๐ŸŸฐ Power (num1^num2)":
result = math.pow(num1, num2)
symbol = "^"
elif operation == "โˆš Square Root of First Number":
if num1 >= 0:
result = math.sqrt(num1)
symbol = "โˆš"
else:
error = "Cannot take square root of a negative number."
elif operation == "% Percentage (num1% of num2)":
result = (num1 / 100) * num2
symbol = "%"
elif operation == "1/x Reciprocal of First Number":
if num1 != 0:
result = 1 / num1
symbol = "1/x"
else:
error = "Reciprocal of 0 is undefined."
# Display result
if error:
st.warning(f"โš ๏ธ {error}")
else:
if operation == "โˆš Square Root of First Number":
st.success(f"Result: โˆš{num1} = {result}")
st.session_state.history.append(f"โˆš{num1} = {result}")
elif operation == "1/x Reciprocal of First Number":
st.success(f"Result: 1/{num1} = {result}")
st.session_state.history.append(f"1/{num1} = {result}")
else:
st.success(f"Result: {num1} {symbol} {num2} = {result}")
st.session_state.history.append(f"{num1} {symbol} {num2} = {result}")
except Exception as e:
st.error(f"An error occurred: {str(e)}")
# Show history
if st.session_state.history:
st.write("### ๐Ÿ“œ Calculation History")
for record in reversed(st.session_state.history[-5:]): # show last 5 only
st.write(record)
# Reset button
if st.button("๐Ÿ”„ Reset Calculator"):
st.session_state.history.clear()
st.experimental_rerun()