python-3.x
  • dictionary
  • 2016-05-24 55 views 0 likes 
    0
    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代碼(如文檔字符串中所示)。我想對基於用戶輸入符號的數字進行操作,但即使我只在字典中保留作爲操作符的符號的值(即,僅「+」:+,「 - 」 : - 等字典)Python:如何使用字典來操作用戶輸入?

    編輯: 我想要更少的代碼,所以請不要告訴我做一個函數來調用。

    +1

    查看['operator'模塊](https://docs.python.org/3/library/operator.html),它提供了常見的操作符作爲函數。 – Evert

    +0

    @Evert thx工作:) –

    回答

    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) 
    

    至少這應該會給你一個想法。

    +0

    我想到的功能,但這會導致更多的代碼(對不起,讓我編輯我的問題更具體)。 –

    相關問題