Python设计一个计算器
时间: 2024-06-09 15:04:10 浏览: 159
设计一个简单的命令行计算器,你可以使用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("Error: Division by zero is not allowed.")
return None
print("Welcome to the Simple Calculator!")
while True:
print("\nOptions:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '5':
break
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if choice == '1':
result = add(num1, num2)
elif choice == '2':
result = subtract(num1, num2)
elif choice == '3':
result = multiply(num1, num2)
elif choice == '4':
result = divide(num1, num2)
else:
print("Invalid choice. Please try again.")
continue
if result is not None:
print(f"Result: {result}")
```
这个程序定义了四个基本的算术操作函数(加、减、乘、除),然后在无限循环中接收用户的输入,执行相应的计算,并显示结果。用户可以选择退出程序。
阅读全文