import gradio as gr def calculator(num1, operation, num2): if operation == "add": return num1 + num2 elif operation == "subtract": return num1 - num2 elif operation == "multiply": return num1 * num2 elif operation == "divide": if num2 == 0: raise gr.Error("Cannot divide by zero!") return num1 / num2 with gr.Blocks(fill_height=True) as demo: gr.Markdown( """ # 🧮 Calculator ### Simple & elegant calculator built with [anycoder](https://huggingface.co/spaces/akhaliq/anycoder) """, elem_classes="header" ) with gr.Row(): with gr.Column(scale=1, min_width=300): num1 = gr.Number( label="First Number", placeholder="0", value=0 ) operation = gr.Radio( choices=[ ("➕ Add", "add"), ("➖ Subtract", "subtract"), ("✖️ Multiply", "multiply"), ("➗ Divide", "divide") ], value="add", label="Operation", container=True ) num2 = gr.Number( label="Second Number", placeholder="0", value=0 ) with gr.Row(): clear_btn = gr.Button("Clear", variant="secondary", size="lg", scale=1) calc_btn = gr.Button("Calculate", variant="primary", size="lg", scale=2) result = gr.Number( label="Result", interactive=False, container=True, scale=1 ) gr.Examples( examples=[ [45, "add", 3], [10, "subtract", 5], [12, "multiply", 8], [100, "divide", 4], ], inputs=[num1, operation, num2], label="Try these examples", examples_per_page=4 ) def clear_all(): return 0, "add", 0, 0 calc_btn.click( fn=calculator, inputs=[num1, operation, num2], outputs=[result], api_visibility="public" ) clear_btn.click( fn=clear_all, inputs=None, outputs=[num1, operation, num2, result] ) # Allow Enter key to calculate num1.submit(calculator, [num1, operation, num2], [result]) num2.submit(calculator, [num1, operation, num2], [result]) if __name__ == "__main__": demo.launch( theme=gr.themes.Soft( primary_hue="blue", secondary_hue="slate", neutral_hue="zinc", font=gr.themes.GoogleFont("Inter"), text_size="lg", spacing_size="lg", radius_size="lg" ).set( button_primary_background_fill="*primary_600", button_primary_background_fill_hover="*primary_700", block_title_text_weight="600", block_label_text_weight="500", ), css=""" .header { text-align: center; padding: 1rem 0 2rem 0; } .header h1 { font-size: 2.5rem; font-weight: 700; margin-bottom: 0.5rem; } .header h3 { font-size: 1rem; font-weight: 400; color: #64748b; } @media (max-width: 768px) { .header h1 { font-size: 2rem; } .header h3 { font-size: 0.9rem; } } """, footer_links=[ {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"} ] )