用python实现一个简单的计算器(while ture循环)
时间: 2024-10-13 19:19:01 浏览: 33
在Python中,我们可以创建一个简单的命令行计算器,利用`while True`循环持续接收用户输入并计算结果,直到用户选择退出。下面是一个基本的例子:
```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("\nSimple Calculator:")
while True:
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 first number: "))
num2 = float(input("Enter second number: "))
try:
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.")
print(f"Result: {result}")
except ValueError:
print("Invalid input. Please enter a number.")
阅读全文