编写有参函数,实现算数运算功能,例如输入2个整数及算数运算符+ - * / %,通过调用该函数可获得算数运算结果
时间: 2023-12-14 19:38:39 浏览: 220
以下是一个示例函数:
```python
def arithmetic_operation(num1, num2, operator):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
return num1 / num2
elif operator == '%':
return num1 % num2
else:
return None
```
该函数有三个参数:num1和num2是要进行运算的两个整数,operator是算数运算符。函数通过判断运算符来决定执行哪种运算,并返回计算结果。如果输入的运算符不是+、-、*、/或%,则返回None。
以下是使用示例:
```python
# 加法
result1 = arithmetic_operation(2, 3, '+')
print(result1) # 输出 5
# 减法
result2 = arithmetic_operation(10, 5, '-')
print(result2) # 输出 5
# 乘法
result3 = arithmetic_operation(3, 4, '*')
print(result3) # 输出 12
# 除法
result4 = arithmetic_operation(10, 3, '/')
print(result4) # 输出 3.3333333333333335
# 取余
result5 = arithmetic_operation(10, 3, '%')
print(result5) # 输出 1
# 非法运算符
result6 = arithmetic_operation(2, 3, '&')
print(result6) # 输出 None
```
阅读全文
相关推荐











