编程实现一个具有两个数加减乘除功能的简单计算器
时间: 2024-10-14 15:08:00 浏览: 55
当然可以,我们可以在Python中编写一个简单的命令行计算器,它允许用户输入两个数字并选择加、减、乘、除操作。以下是一个基础版的实现:
```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 x / y
else:
print("错误:除数不能为零")
return None
def calculator():
while True:
operation = input("请选择运算(+、-、*、/),或者输入 'q' 退出:")
if operation.lower() == 'q':
break
try:
num1 = float(input("请输入第一个数字:"))
num2 = float(input("请输入第二个数字:"))
if operation in ['+', '-', '*', '/']:
result = eval(f"{num1} {operation} {num2}")
print(f"结果是:{result}")
else:
print("无效的运算符,请重新输入")
except ValueError:
print("输入错误,请输入数字")
calculator()
```
在这个程序中,我们首先定义了四个函数分别对应加法、减法、乘法和除法。然后`calculator()`函数循环接收用户的输入,处理计算请求并显示结果。如果用户输入的是非数字或无效运算符,会捕获异常并给出相应的提示。
阅读全文
相关推荐
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)