fahadkhan93's picture
Create app.py
b926acb verified
import gradio as gr
import math
# Store calculation history
history = []
# Calculator function
def scientific_calculator(x, y, operation, mode, clear=False):
global history
if clear:
history = []
return "", []
try:
result = None
deg_to_rad = lambda a: math.radians(a) if mode == "Degrees" else a
if operation == "Addition":
result = x + y
elif operation == "Subtraction":
result = x - y
elif operation == "Multiplication":
result = x * y
elif operation == "Division":
result = x / y if y != 0 else "❌ Cannot divide by zero"
elif operation == "Power (xʸ)":
result = math.pow(x, y)
elif operation == "Square Root (√x)":
result = math.sqrt(x) if x >= 0 else "❌ Invalid input"
elif operation == "Log₁₀(x)":
result = math.log10(x) if x > 0 else "❌ Invalid input"
elif operation == "Natural Log ln(x)":
result = math.log(x) if x > 0 else "❌ Invalid input"
elif operation == "Sin(x)":
result = math.sin(deg_to_rad(x))
elif operation == "Cos(x)":
result = math.cos(deg_to_rad(x))
elif operation == "Tan(x)":
result = math.tan(deg_to_rad(x))
elif operation == "Factorial (x!)":
result = math.factorial(int(x)) if x >= 0 and float(x).is_integer() else "❌ Invalid input"
elif operation == "π (Pi)":
result = math.pi
elif operation == "e (Euler's Number)":
result = math.e
if isinstance(result, float):
result = round(result, 8)
# Track history
label = f"{operation}: {x}" + (f", {y}" if operation in ["Addition", "Subtraction", "Multiplication", "Division", "Power (xʸ)"] else "")
history.append(f"{label} = {result}")
return result, history[-6:]
except Exception as e:
return f"Error: {str(e)}", history[-6:]
# Build UI
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("## 🧠 Scientific Calculator")
with gr.Row():
x = gr.Number(label="Input X", value=0)
y = gr.Number(label="Input Y (optional)", value=0)
operation = gr.Dropdown(
label="Select Operation",
choices=[
"Addition", "Subtraction", "Multiplication", "Division",
"Power (xʸ)", "Square Root (√x)", "Log₁₀(x)", "Natural Log ln(x)",
"Sin(x)", "Cos(x)", "Tan(x)",
"Factorial (x!)", "π (Pi)", "e (Euler's Number)"
],
value="Addition"
)
mode = gr.Radio(choices=["Degrees", "Radians"], value="Degrees", label="Angle Mode (for Trig)")
with gr.Row():
calc_btn = gr.Button("🧮 Calculate")
clear_btn = gr.Button("🧹 Clear History")
result = gr.Textbox(label="Result", interactive=False)
history_box = gr.List(label="History (last 6)")
# Bind buttons
calc_btn.click(
fn=scientific_calculator,
inputs=[x, y, operation, mode],
outputs=[result, history_box]
)
clear_btn.click(
fn=lambda: scientific_calculator(0, 0, "Addition", "Degrees", clear=True),
inputs=[],
outputs=[result, history_box]
)
# Launch
if __name__ == "__main__":
demo.launch()