Skip to the content.

Calculator

import ipywidgets as widgets
from IPython.display import display, clear_output

# Input widgets
num1 = widgets.FloatText(description='Number 1:')
num2 = widgets.FloatText(description='Number 2:')
operation = widgets.Dropdown(
    options=['+', '-', '*', '/'],
    description='Operation:'
)

# Output area
output = widgets.Output()

# Function to calculate and display result
def calculate(b):
    with output:
        clear_output()
        a = num1.value
        b = num2.value
        op = operation.value
        try:
            if op == '+':
                result = a + b
            elif op == '-':
                result = a - b
            elif op == '*':
                result = a * b
            elif op == '/':
                result = a / b
            print(f"Result: {a} {op} {b} = {result}")
        except Exception as e:
            print("Error:", e)

# Button to trigger calculation
calc_button = widgets.Button(description='Calculate')
calc_button.on_click(calculate)

# Display widgets
display(num1, num2, operation, calc_button, output)

FloatText(value=0.0, description='Number 1:')



FloatText(value=0.0, description='Number 2:')



Dropdown(description='Operation:', options=('+', '-', '*', '/'), value='+')



Button(description='Calculate', style=ButtonStyle())



Output()