You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何实现支持加减运算的简单计算器函数?

Simple Addition/Subtraction Calculator Function

No problem at all! Let's put together exactly the calculator function you need. Here's a straightforward implementation in Python, with explanations and test cases to make sure it works as expected:

The Core Function

def calculator(firstArg: int, secondArg: int, operation: str) -> int | str:
    # Handle addition
    if operation == "+":
        return firstArg + secondArg
    # Handle subtraction
    elif operation == "-":
        return firstArg - secondArg
    # Catch invalid operations
    else:
        return "invalid operation"

Breakdown of the Code:

  • Type Hints: We use int for the two number parameters to make it clear we expect integers, and str for the operation. The return type is marked as int | str since it can return either a calculation result (integer) or an error message (string).
  • Condition Checks: We first check if the operation is "+" and return the sum, then check for "-" and return the difference. Any other operation string triggers the error message.

Test It Out!

Here are some quick test cases to verify the function behaves correctly:

# Addition test
print(calculator(7, 2, "+"))  # Output: 9

# Subtraction test
print(calculator(15, 6, "-")) # Output: 9

# Invalid operation test
print(calculator(4, 1, "/"))  # Output: invalid operation

Optional: Add Input Validation

If you want to make sure the function only accepts actual integers (in case someone passes a float or string by mistake), you can add an extra check at the start:

def calculator(firstArg: int, secondArg: int, operation: str) -> int | str:
    # Validate that inputs are integers
    if not isinstance(firstArg, int) or not isinstance(secondArg, int):
        return "invalid number input"
    
    if operation == "+":
        return firstArg + secondArg
    elif operation == "-":
        return firstArg - secondArg
    else:
        return "invalid operation"

That should cover all your requirements! Let me know if you need this adapted to another programming language.

内容的提问来源于stack exchange,提问作者Bruna Florêncio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 22:37:53