1

以下是我所做的:想法是能够从 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

我实际上并没有响应用户的输入,而是假设他会键入 add。如果用户想要减去而不是添加等等,我该如何对其进行编码,以便它会做出不同的反应?求救。

4

2 回答 2

4

You could use a dictionary dispatch and some of the functions in the operator module as a base.

import operator as op

operations = {
    'add': {'func': op.add, 'char': '+'},
    'minus': {'func': op.sub, 'char': '-'}
}

Then lookup the keyword and apply the function and display the equation:

print F1, operations[Equation]['char'], F2, '=', operations[Equation]['func'](F1, F2)
于 2012-10-16T13:30:58.067 回答
0

定义开始():

#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

开始()

有我的计算器记住在你的+、-、*、/上输入,然后再输入数字

于 2019-01-12T22:26:33.973 回答