用switch语句写运算符
时间: 2023-12-26 20:25:38 浏览: 34
根据提供的引用内容,`switch`语句在Python中是不存在的,但是可以使用`if-elif-else`语句来实现类似的功能。下面是一个用`if-elif-else`语句实现运算符的例子:
```python
def calculate(operator, num1, num2):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
return num1 / num2
else:
return "Invalid operator"
print(calculate('+', 2, 3)) # 输出:5
print(calculate('-', 5, 2)) # 输出:3
print(calculate('*', 4, 6)) # 输出:24
print(calculate('/', 10, 2)) # 输出:5.0
print(calculate('%', 5, 2)) # 输出:Invalid operator
```
在上面的例子中,`calculate`函数接收三个参数:运算符,第一个数字和第二个数字。然后,使用`if-elif-else`语句来检查运算符,并执行相应的操作。如果运算符无效,则返回一个错误消息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)