帮我写一个python计算器
时间: 2023-02-18 17:49:55 浏览: 57
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):
return x / y
print("选择运算:")
print("1、相加")
print("2、相减")
print("3、相乘")
print("4、相除")
choice = input("输入你的选择(1/2/3/4):")
num1 = int(input("输入第一个数字: "))
num2 = int(input("输入第二个数字: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("非法输入")
相关问题
帮我写一个python 计算器代码
好的,以下是一个简单的 Python 计算器代码:
```
while True:
try:
num1 = float(input("请输入第一个数字:"))
num2 = float(input("请输入第二个数字:"))
operator = input("请选择运算符(+、-、*、/):")
if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
elif operator == "/":
print(num1 / num2)
else:
print("输入有误,请重新输入!")
except ValueError:
print("输入有误,请重新输入!")
```
希望能帮到你!
写一个python计算器
好的,下面是一个简单的Python计算器实现:
```python
while True:
# 获取用户输入的数学表达式
expr = input("请输入数学表达式(例如:2 + 3)或输入 q 退出:")
# 如果用户输入 q,则退出程序
if expr == "q":
break
# 计算表达式的值
try:
result = eval(expr)
print("结果为:", result)
except:
print("表达式有误,请重新输入")
```
这个计算器可以处理加、减、乘、除等基本的数学运算。用户输入一个数学表达式,程序使用eval()函数计算表达式的值,并将结果输出到屏幕上。如果表达式有误,则程序会提示用户重新输入。当用户输入 q 时,程序会退出。
注意:这个计算器没有进行任何的输入验证和错误处理,仅作为一个简单的示例。在实际开发中,需要根据具体需求进行相应的改进和完善。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)