求助:如何实现支持加减运算的简单计算器函数?
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
intfor the two number parameters to make it clear we expect integers, andstrfor the operation. The return type is marked asint | strsince 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
相关产品推荐
相关产品推荐

