Gianpaolo Macario commited on
Commit
87ab8f9
·
1 Parent(s): 2c2848c

feat(app): add function: calculate()

Browse files
Files changed (1) hide show
  1. app.py +42 -0
app.py CHANGED
@@ -42,6 +42,32 @@ def get_dad_joke():
42
  return data.get("joke", "No joke found.")
43
  else:
44
  return "Failed to retrieve a joke."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  # demo = gr.Interface(fn=greet, inputs="text", outputs="text")
47
  with gr.Blocks() as demo:
@@ -53,4 +79,20 @@ with gr.Blocks() as demo:
53
  joke_output = gr.Textbox(label="Dad Joke")
54
  joke_btn.click(fn=get_dad_joke, outputs=joke_output, api_name="get_dad_joke")
55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  demo.launch(mcp_server=True)
 
42
  return data.get("joke", "No joke found.")
43
  else:
44
  return "Failed to retrieve a joke."
45
+
46
+ def calculate(n1, op, n2):
47
+ """
48
+ Performs basic arithmetic operations between two numbers.
49
+ This function takes two numbers and an operator as input and returns the result
50
+ of the arithmetic operation. Supported operations are addition (+), subtraction (-),
51
+ multiplication (*), and division (/). For division, checks for division by zero.
52
+ Args:
53
+ n1 (float): First number
54
+ op (str): Operator ('+', '-', '*', or '/')
55
+ n2 (float): Second number
56
+ Returns:
57
+ float: Result of the arithmetic operation if valid
58
+ str: "Error" if invalid operation (like division by zero)
59
+ Examples:
60
+ >>> calculate(10, "+", 5)
61
+ 15
62
+ >>> calculate(10, "/", 0)
63
+ "Error"
64
+ """
65
+
66
+ if op == "+": return n1 + n2
67
+ if op == "-": return n1 - n2
68
+ if op == "*": return n1 * n2
69
+ if op == "/" and n2 != 0: return n1 / n2
70
+ return "Error"
71
 
72
  # demo = gr.Interface(fn=greet, inputs="text", outputs="text")
73
  with gr.Blocks() as demo:
 
79
  joke_output = gr.Textbox(label="Dad Joke")
80
  joke_btn.click(fn=get_dad_joke, outputs=joke_output, api_name="get_dad_joke")
81
 
82
+ with gr.Row():
83
+ num1 = gr.Number(label="First Number")
84
+ operation = gr.Dropdown(
85
+ choices=["+", "-", "*", "/"],
86
+ label="Operation"
87
+ )
88
+ num2 = gr.Number(label="Second Number")
89
+
90
+ calc_btn = gr.Button("Calculate")
91
+ calc_output = gr.Number(label="Result")
92
+ calc_btn.click(
93
+ fn=calculate,
94
+ inputs=[num1, operation, num2],
95
+ outputs=calc_output,
96
+ api_name="calculate")
97
+
98
  demo.launch(mcp_server=True)