用python函数实现四则运算
时间: 2024-05-05 09:19:56 浏览: 90
计算器实现四则运算
可以使用以下代码实现四则运算:
```python
def calculate(num1, num2, operator):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
return num1 / num2
else:
return "Invalid operator"
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
operator = input("Enter operator (+, -, *, /): ")
result = calculate(num1, num2, operator)
print("Result: ", result)
```
你可以输入两个数字和运算符,然后调用 `calculate()` 函数来执行运算并返回结果。
阅读全文