从键盘输入两个数字并选择一种四则运算,然后输出运算结果。要求用不同的函数来实现四则运算,并定义一个接收两个操作数和一个函数名称的函数,函数名称指定要做哪种运算。
时间: 2023-07-16 10:14:13 浏览: 53
可以使用以下代码实现:
```python
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error: division by zero"
else:
return x / y
def calculate(x, y, operation):
if operation == "add":
return add(x, y)
elif operation == "subtract":
return subtract(x, y)
elif operation == "multiply":
return multiply(x, y)
elif operation == "divide":
return divide(x, y)
else:
return "Error: invalid operation"
x = float(input("Enter first number: "))
y = float(input("Enter second number: "))
operation = input("Enter operation (add/subtract/multiply/divide): ")
result = calculate(x, y, operation)
print("Result: ", result)
```
首先定义了四个函数分别实现加、减、乘、除四种运算,然后定义了一个 `calculate` 函数来接收两个操作数和一个运算符,并根据运算符来调用相应的函数计算结果。最后从键盘输入两个数字和运算符,然后调用 `calculate` 函数计算结果并输出。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)