Python:如何使用字典来操作用户输入?

时间:2016-05-24 08:11:49

标签: 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: "))
            #trying to use a dictionary instead of "if" statements present in docstring
            dictionary = {"+": answer += number, "-": answer -= number, "*": answer *= number, "/": answer /= number, "^": answer **= number}
            dictionary[symbol]
            """if symbol == "+":
                answer += number
            if symbol == "-":
                answer -= number
            if symbol == "*":
                answer *= number
            if symbol == "/":
                answer /= number
            if symbol == "^":
                answer **= number"""

我觉得有一堆“if”语句是WET代码(如docstring中所示)。我想根据用户输入的符号对数字进行操作,但是即使我只将符号的值保留为字典中的运算符(即仅“+”:+,“ - ”),它也会显示“无效语法” : - 等在字典中)

修改 我想要更少的代码,所以请不要告诉我调用函数。

1 个答案:

答案 0 :(得分:0)

您必须为操作定义函数并将它们存储在字典中。类似的东西:

def plus (a, b):
  return a+b

def minus (a, b):
  return a-b

my_dict = {"+" : plus, "-" : minus}

answer = my_dict[symbol](answer, number)

至少这应该会给你一个想法。