Shahbaz Akbar
Update app.py
2ac5338 verified
import streamlit as st
import math
# --- Set Page Configuration ---
st.set_page_config(page_title="Advanced Calculator", page_icon="๐Ÿงฎ", layout="centered")
# --- Initialize Calculation History ---
if "history" not in st.session_state:
st.session_state.history = []
# --- UI: Title and Description ---
st.title("๐Ÿงฎ Advanced Web-Based Calculator")
st.write("Perform basic and advanced arithmetic operations with a clean and interactive UI.")
# --- User Input Fields ---
num1 = st.number_input("Enter First Number", value=0.0, format="%.6f")
num2 = st.number_input("Enter Second Number (if required)", value=0.0, format="%.6f")
# --- Dropdown for Operation Selection ---
operation = st.selectbox(
"Select Operation",
[
"Addition (+)", "Subtraction (-)", "Multiplication (ร—)", "Division (รท)",
"Modulus (%)", "Exponentiation (x^y)", "Square Root (โˆšx)",
"Logarithm (log base 10)", "Natural Log (ln)",
"Sine (sin)", "Cosine (cos)", "Tangent (tan)"
]
)
# --- Perform Calculation ---
result = None
if st.button("Calculate"):
try:
if operation == "Addition (+)":
result = num1 + num2
elif operation == "Subtraction (-)":
result = num1 - num2
elif operation == "Multiplication (ร—)":
result = num1 * num2
elif operation == "Division (รท)":
if num2 == 0:
st.error("โŒ Error: Division by zero is not allowed!")
else:
result = num1 / num2
elif operation == "Modulus (%)":
if num2 == 0:
st.error("โŒ Error: Modulus by zero is not allowed!")
else:
result = num1 % num2
elif operation == "Exponentiation (x^y)":
result = num1 ** num2
elif operation == "Square Root (โˆšx)":
if num1 < 0:
st.error("โŒ Error: Square root of negative number is not allowed!")
else:
result = math.sqrt(num1)
elif operation == "Logarithm (log base 10)":
if num1 <= 0:
st.error("โŒ Error: Logarithm of zero or negative number is not allowed!")
else:
result = math.log10(num1)
elif operation == "Natural Log (ln)":
if num1 <= 0:
st.error("โŒ Error: Natural logarithm of zero or negative number is not allowed!")
else:
result = math.log(num1)
elif operation == "Sine (sin)":
result = math.sin(math.radians(num1)) # Convert degrees to radians
elif operation == "Cosine (cos)":
result = math.cos(math.radians(num1))
elif operation == "Tangent (tan)":
result = math.tan(math.radians(num1))
# Store in History
if result is not None:
calculation = f"{num1} {operation.split()[1]} {num2 if 'โˆš' not in operation else ''} = {result}"
st.session_state.history.append(calculation)
st.success(f"โœ… Result: {result}")
except Exception as e:
st.error(f"โš ๏ธ An error occurred: {e}")
# --- Show Calculation History ---
if st.session_state.history:
st.subheader("๐Ÿ“œ Calculation History")
for calc in st.session_state.history[-5:]: # Show last 5 calculations
st.write(calc)
# --- Footer ---
st.markdown("---")
st.markdown("๐Ÿ”น Developed using **Streamlit** | ๐Ÿš€ Ready for **Hugging Face Spaces** Deployment")