用python函数实现四则运算
时间: 2024-04-30 18:17:47 浏览: 5
可以通过定义一个函数来实现四则运算,下面是一个示例代码:
```python
def arithmetic_operation(num1, num2, operator):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
if num2 == 0:
return "除数不能为0"
else:
return num1 / num2
else:
return "不支持的操作符"
# 示例
print(arithmetic_operation(1, 2, '+')) # 输出:3
print(arithmetic_operation(5, 3, '-')) # 输出:2
print(arithmetic_operation(2, 4, '*')) # 输出:8
print(arithmetic_operation(6, 3, '/')) # 输出:2.0
print(arithmetic_operation(6, 0, '/')) # 输出:"除数不能为0"
print(arithmetic_operation(3, 5, '%')) # 输出:"不支持的操作符"
```
在上面的示例代码中,我们定义了一个 `arithmetic_operation` 函数,接收三个参数:`num1` 和 `num2` 代表参与运算的两个数,`operator` 代表运算符。在函数内部,我们通过 if-elif-else 语句判断运算符,并返回计算结果。注意,我们还特判了除数为0的情况。在函数外部,我们对函数进行了多组测试。