如何根据用户输入访问字典中的数学运算?

时间:2016-05-24 10:07:01

标签: python python-3.x dictionary

def calculator():
    print("When prompted to enter a symbol, enter:\n'+' to add,\n'-' to subtract,\n'*' to multiply,\n'/' to divide,\n'^' to calculate powers,")
    print("',\n'=' to get the answer.")
    again = None
    while again != "x":
        answer = float(input("\nEnter number: "))
        while 1 == 1:
            symbol = input("Enter symbol: ")
            if symbol == "=":
                print("\nThe answer is ", answer, ".", sep = "")
                again = input("\nEnter 'a' to use the calculator again and 'x' to exit: ")
                break
            number = float(input("Enter number: "))
            dictionary = {"+": operator.iadd(answer, number), "-": operator.isub(answer, number), "*": operator.imul(answer, number), "/": operator.itruediv(answer, number), "^": operator.ipow(answer, number)}
            dictionary[symbol]

该程序似乎有效,但每当我要求答案时,它只显示我输入的第一个数字;它似乎根本没有使用字典。

1 个答案:

答案 0 :(得分:0)

您没有将运算符方法的结果分配回answer

dictionary = {
    "+": operator.iadd(answer, number), 
    "-": operator.isub(answer, number), 
    "*": operator.imul(answer, number), 
    "/": operator.itruediv(answer, number), 
    "^": operator.ipow(answer, number)
}

answer = dictionary[symbol]

或者,更好的方法是只存储方法:

dictionary = {
    "+": operator.iadd, 
    "-": operator.isub, 
    "*": operator.imul, 
    "/": operator.itruediv, 
    "^": operator.ipow
}

answer = dictionary[symbol](answer, number)