以下是一个非常基础的命令行版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:
return "Error: Division by zero is not allowed."
print("Select operation:")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
choice = input("Enter choice(1/2/3/4): ")
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
result = divide(num1, num2)
if isinstance(result, str):
print(result)
else:
print(num1, "/", num2, "=", result)
else:
print("Invalid Input")
这个简单的计算器程序首先定义了四个函数分别对应加、减、乘、除操作。然后,程序会循环询问用户想要进行的操作,并根据用户的输入执行相应的计算并显示结果。如果用户尝试除以零,程序将返回错误信息。