编写一个交互式Python计算器程序。
时间: 2024-09-18 20:19:04 浏览: 47
编写一个交互式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("\nChoose an operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
choice = input("Enter your choice (1/2/3/4/5): ")
if choice == '5':
break
num1 = float(input("Enter first number: "))
num2 = float(input("Enter 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.")
if result is not None:
print(f"Result: {result}")
print("Thank you for using the calculator. Goodbye!")
```
在这个程序中,用户可以选择加、减、乘、除四种运算,然后输入两个数字,程序会计算并显示结果。如果选择的是退出操作或除数为零,程序会给出相应的提示。
阅读全文