switch 语句编写一个简单的四则运算
时间: 2023-05-26 12:03:01 浏览: 111
```python
def calculate(operator: str, num1: float, num2: float) -> float:
"""
A simple function to perform arithmetic operations on num1 and num2 based on the operator provided.
"""
result = 0
# Use switch case to implement arithmetic operations
switcher = {
'+': num1 + num2,
'-': num1 - num2,
'*': num1 * num2,
'/': num1 / num2
}
result = switcher.get(operator, "Invalid operator")
return result
# Example usage
print(calculate('+', 5, 3)) # Output: 8
print(calculate('-', 5, 3)) # Output: 2
print(calculate('*', 5, 3)) # Output: 15
print(calculate('/', 5, 3)) # Output: 1.6666666666666667
print(calculate('^', 5, 3)) # Output: Invalid operator
```
阅读全文