2016-09-30 67 views
-2

當用戶輸入一個名稱(例如「Jim」)作爲我的「Test」類的實例的參數時,def find函數被調用,並且for循環遍歷匹配「Jim」的字典中的所有名稱。如果def find在字典中找到關鍵字「Jim」,那麼它應該打印出相應的值。但是當我運行代碼時,它只是說「無」。我需要更改什麼,以便在打印語句「工作」中調用def find如何通過字典中的鍵循環找到相應的值?

class Test(object): 
    def __init__(self, x=0): # error in (def find)? 
     self.x = x 

    c = None     # error while looping in the for loop? 
    users = { 
     'John': 1, 
     'Jim': 2, 
     'Bob': 3 
    } 

    def find(self, x):  # The user is supposed to type in the name "x" 

     for self.c in self.users:   # it goes through the dictionary 
      if x == self.users[self.c]: # If x is equal to key it prints worked 
       print('worked') 
      else: 
       pass 


beta = Test() 
print(beta.find('Jim')) 
+0

'for'循環需要縮進。 – techydesigner

+0

另外'else'需要縮進。 – techydesigner

+0

這只是複製和粘貼 – PrQ

回答

2

@ nk001,
我覺得這是一個有點更像你想什麼:

class Test(object): 
    def __init__(self, x=0): 
     self.x = x    # <-- indent the __init__ statements 

    users = {     # <-- users = { 
     'John': 1,    #   KEY: VALUE, 
     'Jim': 2,    #   KEY: VALUE, 
     'Bob': 3    #   KEY: VALUE, 
    }       #  } 

    def find(self, x):    # <-- The user passes the "x" argument 

     for i in self.users:  # <-- Now it goes through the dictionary 
      if x == i:    # <-- If ARGV('x') == KEY 
       return 'worked' # <-- Then RETURN 'worked' 
      else: 
       pass 


beta = Test() 
print(beta.find("Jim"), beta.users["Jim"]) 

有幾種不同的方法來獲得「工作」味精和相應的價值印刷,這只是一個演示訪問字典[KEY]來獲取VALUE的例子。

另外,我只是假設你的意思是一個if/else塊,而不是for/else?縮進對於Python來說至關重要。另外,原始腳本返回None,因爲for循環中沒有明確的return - 因此,當函數在打印語句print(beta.find('Jim'))中調用時,函數完成時它將返回任何內容(「None」)。希望有所幫助!

1

我寫了一個工作代碼:

class Test(object): 
    users = { 
     'John': 1, 
     'Jim': 2, 
     'Bob': 3 
    } 

    def __init__(self, x=0): # So I don't get an error in (def find) 
     self.x = x 

    def find(self, x): # The user is suppose to type in the name "x" 
     for name in Test.users.keys(): # it goes through the dictionary 
      if x == name: # If x is equal to key it prints worked 
       print('worked', self.users[name]) 
      else: 
       pass 


beta = Test() 
beta.find('Jim') 
  1. 你不不需要self.c
  2. users是一個類變量,你需要通過Test.users來訪問它。
  3. 你的名字被存儲爲字典的鍵。所以你需要通過Test.users.keys()
  4. 得到他們聲明print(beta.find('Jim'))將打印返回值的find。但是您不會手動返回值,您將在輸出中獲得None
+0

@nk001,注意你對'print'和'print'(beta.find('Jim'))和@ yundongxu的'beta.find('Jim')' –