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()