编写一个 Python 程序,根据用户选择的选项执行加法、减法、乘法和除法运算,制作一个简单的计算器。
Python 编写简单计算器程序
下面的程序会打印每种选项及其相应数字的消息。在此,选项 1 = 加法,2 = 减法,3 = 乘法,4 = 除法。然后,它会要求用户选择他们想要的操作。输入选项 1、2、3 和 4 的用户是有效的;其他任何输入都是无效的。
在下面的 行 中,我们使用了两个整数类型的 input() 语句来允许用户输入两个数字。接下来,elif 语句 根据用户的选项执行简单的计算。
print('''please Select the Operation you want to Perfom
1 = Add
2 = Subtract
3 = Multiply
4 = Divide''')
opt = int(input("Choose Operation from 1, 2, 3, 4 = "))
n1 = int(input("First Number = "))
n2 = int(input("Second Number = "))
if opt == 1:
print(n1, ' + ', n2, ' = ', n1 + n2)
elif opt == 2:
print(n1, ' - ', n2, ' = ', n1 - n2)
elif opt == 3:
print(n1, ' * ', n2, ' = ', n1 * n2)
elif opt == 4:
print(n1, ' / ', n2, ' = ', n1 / n2)
else:
print('Invalid Input')

使用函数的简单计算器
在这个计算器程序中,我们创建了加法 (x, y)、减法 (x, y)、乘法 (x, y) 和除法 (x, y) 函数来进行计算。在 print 语句中,我们直接调用了这些 函数。
def addition(x, y):
return x + y
def subtraction(x, y):
return x - y
def multiplication(x, y):
return x * y
def division(x, y):
return x / y
opt = int(input("Choose Operation from 1(Add), 2(Sub), 3(Multi), 4(Div) = "))
n1 = int(input("First Number = "))
n2 = int(input("Second Number = "))
if opt == 1:
print(n1, ' + ', n2, ' = ', addition(n1, n2))
elif opt == 2:
print(n1, ' - ', n2, ' = ', subtraction(n1, n2))
elif opt == 3:
print(n1, ' * ', n2, ' = ', multiplication(n1, n2))
elif opt == 4:
print(n1, ' / ', n2, ' = ', divison(n1, n2))
else:
print('Invalid Input')
