Calculator-app / app.py
Subayyal's picture
Update app.py
baec084 verified
import streamlit as st
import numpy as np
st.set_page_config(page_title="Scientific Calculator", page_icon="🧮", layout="centered")
st.title("🧮 Scientific Calculator")
# --- Session states for memory & history ---
if "memory" not in st.session_state:
st.session_state.memory = 0
if "history" not in st.session_state:
st.session_state.history = []
# Input fields
num1 = st.number_input("Enter first number:", format="%.6f")
num2 = st.number_input("Enter second number (optional for unary ops):", format="%.6f", value=0.0)
# Operation selection
operation = st.selectbox(
"Select operation:",
[
"Add", "Subtract", "Multiply", "Divide",
"Power", "Square Root (num1)", "Logarithm (num1)",
"Sine (num1)", "Cosine (num1)", "Tangent (num1)"
]
)
# Perform calculation
result = None
if st.button("Calculate"):
try:
if operation == "Add":
result = num1 + num2
elif operation == "Subtract":
result = num1 - num2
elif operation == "Multiply":
result = num1 * num2
elif operation == "Divide":
if num2 != 0:
result = num1 / num2
else:
st.error("Division by zero is not allowed.")
elif operation == "Power":
result = num1 ** num2
elif operation == "Square Root (num1)":
result = np.sqrt(num1)
elif operation == "Logarithm (num1)":
if num1 > 0:
result = np.log(num1)
else:
st.error("Logarithm is only defined for positive numbers.")
elif operation == "Sine (num1)":
result = np.sin(np.radians(num1))
elif operation == "Cosine (num1)":
result = np.cos(np.radians(num1))
elif operation == "Tangent (num1)":
result = np.tan(np.radians(num1))
if result is not None:
st.success(f"Result: {result}")
st.session_state.history.append(f"{operation}: {result}")
except Exception as e:
st.error(f"Error: {str(e)}")
# --- Memory Functions ---
st.subheader("Memory Functions")
col1, col2, col3 = st.columns(3)
with col1:
if st.button("M+"):
if result is not None:
st.session_state.memory += result
with col2:
if st.button("M-"):
if result is not None:
st.session_state.memory -= result
with col3:
if st.button("MC"):
st.session_state.memory = 0
st.info(f"Memory: {st.session_state.memory}")
# --- History ---
st.subheader("Calculation History")
if st.session_state.history:
for h in st.session_state.history[-10:][::-1]: # show last 10
st.write(h)
else:
st.write("No calculations yet.")