import streamlit as st import math # Page config st.set_page_config(page_title="Scientific Calculator", layout="centered") # --- CSS Styling --- st.markdown(""" """, unsafe_allow_html=True) # --- State --- if "expression" not in st.session_state: st.session_state.expression = "" if "history" not in st.session_state: st.session_state.history = [] # --- Functions --- def add(symbol): st.session_state.expression += str(symbol) def clear(): st.session_state.expression = "" def calculate(): try: expr = st.session_state.expression expr = expr.replace("^", "**").replace("√", "math.sqrt") expr = expr.replace("π", str(math.pi)).replace("e", str(math.e)) expr = expr.replace("ln", "math.log").replace("log", "math.log10") for func in ["sin", "cos", "tan"]: expr = expr.replace(func, f"math.{func}") result = eval(expr) result_str = f"{st.session_state.expression} = {result}" st.session_state.history.insert(0, result_str) st.session_state.expression = str(result) except: st.session_state.expression = "Error" def handle_input(): expr = st.session_state["input_expr"] st.session_state.expression = expr # --- Layout --- st.markdown("
", unsafe_allow_html=True) # Input via keyboard st.text_input("Type your expression (keyboard supported):", value=st.session_state.expression, key="input_expr", on_change=handle_input) # Display area st.markdown(f"
{st.session_state.expression}
", unsafe_allow_html=True) # Button layout button_rows = [ ["sin(", "cos(", "tan(", "√("], ["log(", "ln(", "π", "e"], ["7", "8", "9", "/"], ["4", "5", "6", "*"], ["1", "2", "3", "-"], ["0", ".", "^", "+"], ["(", ")", "C", "="], ] for row in button_rows: cols = st.columns(4) for i, label in enumerate(row): if label == "=": cols[i].button(label, on_click=calculate) elif label == "C": cols[i].button(label, on_click=clear) else: cols[i].button(label, on_click=add, args=(label,)) # History section if st.session_state.history: st.markdown("
History
", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) for entry in st.session_state.history[:10]: st.markdown(f"- {entry}") st.markdown("
", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True)