使用Python的基本计算器程序
在此程序中,我们将看到如何使用python程序完成计算器的基本计算器功能。在这里,我们创建了单个函数来执行计算并返回结果。用户输入以及运算符的选择也被接受。
示例
# This function performs additiion
def add(a, b):
return a + b
# This function performs subtraction
def subtract(a, b):
return a - b
# This function performs multiplication
def multiply(a, b):
return a * b
# This function performs division
def divide(a, b):
return a / b
print("选择一个操作。")
print("+")
print("-")
print("*")
print("/")
# User input
choice = input("输入要使用的运算符:")
A = int(input("Enter first number: "))
B = int(input("Enter second number: "))
if choice == '+':
print(A,"+",B,"=", add(A,B))
elif choice == '-':
print(A,"-",B,"=", subtract(A,B))
elif choice == '*':
print(A,"*",B,"=", multiply(A,B))
elif choice == '/':
print(A,"/",B,"=", divide(A,B))
else:
print("Invalid input")输出结果
运行上面的代码给我们以下结果-
选择一个操作。 + - * / 输入要使用的运算符: - Enter first number: 34 Enter second number: 20 34 - 20 = 14