以下是我所做的:想法是能够根据用户是想添加,减去,除法还是乘法来计算2个数字的结果。
print 'Welcome to my calculator program'
Equation = raw_input('You want to add, subtract, divide or multiply? '
firstno = raw_input ('Please enter first number ')
secondno = raw_input('Please enter second number ')
F1 = int(firstno)
F2 = int(secondno)
F3 = F1 + F2
print F1, '+' ,F2, '=' ,F3
我实际上并没有回应用户的输入,而是假设他会键入添加。我如何对其进行编码,以便在用户想要减去而不是添加等时它会有不同的反应?请求帮助。
答案 0 :(得分:4)
您可以使用字典调度和operator
模块中的一些函数作为基础。
import operator as op
operations = {
'add': {'func': op.add, 'char': '+'},
'minus': {'func': op.sub, 'char': '-'}
}
然后查找关键字并应用该函数并显示等式:
print F1, operations[Equation]['char'], F2, '=', operations[Equation]['func'](F1, F2)
答案 1 :(得分:0)
def start():
#main input variable to get a sign to do
calculator = input('What would you like to calculate? (x, /, +, -): ')
#gets 2 #'s to multiply, add, subtract, or divide
if (calculator) == ('+'):
add = input('what is the frist number would you like to add? ')
addi = input('what is the second number would you like to add? ')
elif (calculator) ==('-'):
sub = input('what is the first number would you like to subtract? ')
subt = input('what is the second number you would like to subtract? ')
elif (calculator) == ('/'):
div = input('what is the first number would you like to divide? ')
divi = input('what is the second number would you like to divide? ')
elif (calculator) == ('x'):
mult = input('what is the first number would you like to multiply? ')
multi = input('what is the second number would you like to multiply? ')
#failsafe if done incorrect
elif (calculator) != ('x', '/', '-', '+'):
print('try again')
return
#adds 2 inputted #'s
if calculator == '+' :
sumAdd = float (add) + float (addi)
print(sumAdd)
#multiplies the 2 inputted #'s
elif calculator == 'x' :
sumMul = float (mult) * float (multi)
print(sumMul)
#divides the 2 inputted #'s
elif calculator == '/' :
sumDiv = float (div) / float (divi)
print(sumDiv)
#subtracting the 2 inputted #'s
elif calculator == '-' :
sumSub = float (sub) - float (subt)
print(sumSub)
#returns to top of code to do another setup
return
start()
有我的计算器 在跳入数字之前,请记住输入+,-,*,/