muhammadrazapathan's picture
Create app.py
d7ed6ed verified
import streamlit as st
import math
import pandas as pd
st.set_page_config(page_title="Mobile Calculator", page_icon="🧮", layout="centered")
# ---------------- SESSION STATE ----------------
if "expression" not in st.session_state:
st.session_state.expression = ""
if "history" not in st.session_state:
st.session_state.history = []
# ---------------- SAFE EVAL ----------------
def safe_eval(expr):
allowed = {
"sqrt": math.sqrt,
"sin": math.sin,
"cos": math.cos,
"tan": math.tan,
"log": math.log10,
"pi": math.pi,
"e": math.e
}
try:
return eval(expr, {"__builtins__": None}, allowed)
except:
return "Error"
# ---------------- STYLE ----------------
st.markdown("""
<style>
body {background-color:#0f172a;}
.display {
background:#1e293b;
color:white;
padding:20px;
border-radius:20px;
font-size:32px;
text-align:right;
margin-bottom:15px;
}
.stButton>button {
height:65px;
border-radius:20px;
font-size:22px;
font-weight:bold;
}
</style>
""", unsafe_allow_html=True)
st.title("🧮 Advanced Mobile Calculator")
# ---------------- DISPLAY ----------------
st.markdown(f"<div class='display'>{st.session_state.expression or '0'}</div>", unsafe_allow_html=True)
if st.session_state.expression:
st.write("Result:", safe_eval(st.session_state.expression))
# ---------------- BUTTON FUNCTIONS ----------------
def add(val):
st.session_state.expression += str(val)
def clear():
st.session_state.expression = ""
def delete():
st.session_state.expression = st.session_state.expression[:-1]
def calculate():
result = safe_eval(st.session_state.expression)
st.session_state.history.append(f"{st.session_state.expression} = {result}")
st.session_state.expression = str(result)
# ---------------- FIXED MOBILE GRID ----------------
layout = [
["C", "DEL", "(", ")"],
["7", "8", "9", "/"],
["4", "5", "6", "*"],
["1", "2", "3", "-"],
["0", ".", "+", "="],
]
for r, row in enumerate(layout):
cols = st.columns(4)
for c, button in enumerate(row):
key_name = f"btn_{r}_{c}"
if button == "C":
cols[c].button(button, key=key_name, on_click=clear)
elif button == "DEL":
cols[c].button(button, key=key_name, on_click=delete)
elif button == "=":
cols[c].button(button, key=key_name, on_click=calculate)
else:
cols[c].button(
button,
key=key_name,
on_click=add,
args=(button,)
)
st.markdown("---")
# ---------------- SCIENTIFIC BUTTONS ----------------
st.subheader("Scientific")
sci_buttons = ["sqrt(", "sin(", "cos(", "tan(", "log(", "pi", "e"]
cols = st.columns(len(sci_buttons))
for i, btn in enumerate(sci_buttons):
cols[i].button(
btn,
key=f"sci_{i}",
on_click=add,
args=(btn,)
)
st.markdown("---")
# ---------------- HISTORY ----------------
st.subheader("History")
if st.session_state.history:
for item in reversed(st.session_state.history):
st.write(item)
df = pd.DataFrame(st.session_state.history, columns=["Calculations"])
st.download_button(
"Download History",
df.to_csv(index=False),
file_name="history.csv"
)
else:
st.info("No calculations yet.")