Python电子计算器
时间: 2024-06-23 22:01:43 浏览: 5
Python是一种功能强大的编程语言,非常适合编写电子计算器。下面是一个简单的Python代码实现,它包含了基本的加减乘除操作:
```python
class Calculator:
def add(self, num1, num2):
return num1 + num2
def subtract(self, num1, num2):
return num1 - num2
def multiply(self, num1, num2):
return num1 * num2
def divide(self, num1, num2):
if num2 != 0:
return num1 / num2
else:
return "Error: Division by zero is not allowed."
def main():
calculator = Calculator()
print("Enter 'add', 'subtract', 'multiply', or 'divide':")
operation = input()
if operation in ['add', 'subtract', 'multiply', 'divide']:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = getattr(calculator, operation)(num1, num2)
print(f"{operation}: {num1} {operation} {num2} = {result}")
else:
print("Invalid operation.")
if __name__ == "__main__":
main()
```
在这个例子中,`Calculator`类定义了四个方法对应四种基本运算。用户可以通过`main`函数交互式地选择运算并输入数字。注意这里使用了`getattr`函数动态获取类的方法,以实现对不同运算的支持。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.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)