calculator计算器python
时间: 2023-11-22 09:50:32 浏览: 49
以下是一个简单的Python计算器的实现,包括加、减、乘、除和取模运算:
```python
class Calculator:
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def divide(self, x, y):
if y == 0:
raise ValueError("Cannot divide by zero!")
return x / y
def modulo(self, x, y):
return x % y
calc = Calculator()
while True:
try:
x = float(input("Enter first number: "))
y = float(input("Enter second number: "))
op = input("Enter operator (+,-,*,/, %): ")
if op == '+':
result = calc.add(x, y)
elif op == '-':
result = calc.subtract(x, y)
elif op == '*':
result = calc.multiply(x, y)
elif op == '/':
result = calc.divide(x, y)
elif op == '%':
result = calc.modulo(x, y)
else:
raise ValueError("Invalid operator!")
print("Result: ", result)
except ValueError as e:
print("Error: ", e)
except KeyboardInterrupt:
print("Exiting calculator...")
break
```
运行程序后,用户将被提示输入两个数字和运算符。程序将根据用户输入的运算符执行相应的操作,并输出结果。如果用户输入的运算符无效或除数为零,则会引发异常并显示错误消息。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)