2015-04-20 46 views
2

我一直在做我能想到的任何事情,現在已經到了我不知道要去哪裏的地步。谷歌搜索錯誤和一般字典幫助後,我已經在這裏結束了...Python 3 Dictionary「list indices need to be integers not str」

我還沒有完成它,主要的底部沒有照顧,所以無視它。初步測試發現了這個錯誤,我不喜歡在開始時沒有開發一個程序,因爲我對Python很新。 (這也是我在這個論壇上的第一篇文章,所以,如果事情是不及格,請讓我知道)

def create(name, age): 
    contact = { 
     'name' : name, 
     'age' : age, 
     'email' : 'email', 
     'phone' : 'phone', 
     } 



def getName(contact): 
    name = input("What's their name? ") 
    return contact[name] 


def getAge(contact): 
    age = int(input("What's their age? ")) 
    return contact ["name"] 

def getPhone(contact): 
    phone = input("What's their phone number? ") 
    return contact['phone'] 

def getEmail(contact): 
    email = input("What's their email? ") 
    return contact['email'] 




def setName(contact, name): 
    contact['name'] = name 

def setAge(contact, age): 
    contact['age'] = age 

def setPhone(contact, phone): 
    contact['phone'] = phone 

def setEmail(contact, phone): 
    contact['email'] = email 

def birthday(contact): 
    a = getAge(contact) 
    a +=1 
    setAge(contact, a) 

def show(contact): 
    print("Name: ", name) 
    print("Phone number: ", phone) 
    print("Age: ", age) 
    print("Email: ", email) 



def main(): 
    ann = create('Ann', 21) 
    roland = create('Roland', 18) 
    john = create ('John' , 19) 
    print(getName("contact")) 
    getAge() 
    getPhone() 
    getEmail() 
    setName() 
    setAge() 
    setPhone() 
    setEmail() 
    show() 


if __name__ == "__main__": 
    main() 
+2

你有什麼期望'的getName(「接觸」)'去做? – jwodder

+0

預期產量是多少? –

+2

你不是從'create()'函數返回創建的字典。另外,你在main()中的調用對我來說並不清楚,除了創建之外基本上沒有任何意義。您必須將創建的字符串作爲參數傳遞... –

回答

1

你應該做的第一件事就是從create()返回接觸dict,像這樣:

def create(name, age): 
    return {'name': name, 
      'age': age, 
      'email': None, 
      'phone': None} 

這樣,你將有機會獲得,是由函數調用中創建的dict

>>> john = create('John', 42) 
>>> john 
{'name': 'John', 'age': 42, 'email': None, 'phone': None} 
>>> john['name'] == 'John' 
True 
>>> john['age'] == 42 
True 

否則會做導致TypeError。嘗試在當前實現的返回值create()上調用任何setter函數時,您會看到相同的錯誤。看看下面的功能:

def set_name(contact, name): 
    contact['name'] = name 

set_name()期待一個dict它將通過改變'name'關鍵的name值的值修改。如果contactNone,這將不起作用。


則是問有關的錯誤是你實現以下功能的結果:

def get_name(contact): 
    name = input("What's their name? ") 
    return contact[name] 

如果我們通過身體走路,我們將看到以下,假設我們把它叫做你的方式在你的示例代碼所做的:(get_name('contact')

>>> name == '<user input>' 
True 
>>> contact == 'contact' 
True 

所以,當函數試圖從contact閱讀他們的關鍵name實際上試圖讀取字符串"contact"的字符索引,它只將整數作爲索引。該功能可能應該讀的東西,如:

def get_name(contact): 
    return contact['name'] 

這樣可以讓你做到以下幾點:(使用相同john如上)

>>> get_name(john) 
'John'