2011-10-17 85 views
1

我有我的数组作业问题,我需要输入一个名字,那么程序必须返回数字,但我可以把它做的是恢复所有的人都电话号码查找程序

def main(): 
    people = ['todd','david','angela','steve','bob','josh','ben'] 
    phoneNumbers = ['234-7654','567-1234','888-8745','789-5489','009-7566','444-6990','911-9111'] 

    found = False 
    index = 0 

    searchValue = raw_input('Enter a name to search for phone number: ') 

    while found == False and index < len(people): 
     if people[index] == searchValue: 
      found = True 
     else: 
      index = index + 1 

    if found: 
     print 'the phone number is: ',phoneNumbers 
    else: 
     print 'that name was not found' 

main() 
+1

你必须使用数组吗?字典在这里是一个更好的数据类型... – tobyodavies

回答

3

使用index打印你想要的电话号码,而不是所有的人:

if found: 
    print 'the phone number is: ', phoneNumbers[index] 
+0

非常感谢你 – dmpinder

0

也许尝试这个:

... 

searchValue = raw_input(.... 

people_numbers = dict(zip(people,phoneNumbers)) 
if searchValue in people_numbers: 
    print 'the phone number is :', people_numbers[searchValue] 
else: 
    print '..... 
1

在行:

print 'the phone number is: ',phoneNumbers 

您应该使用

print 'the phone number is: ',phoneNumbers[index] 

另一种最佳的选择与字典类似做到这一点:

contacts = {'todd':'123-456', 'mauro': '678-910'} 
searchValue = raw_input('Enter a name to search for phone number: ') 

if contacts.has_key(searchValue): 
    print 'The %s phone number is %s' %(searchValue, contacts[searchValue]) 
else: 
    print 'that name was not found' 
2

其他人已经明确给出你答案,但基于在写这个问题的方式上,我担心理解。所以我会详细介绍一下。现在,你的代码被写入的方式,你告诉程序打印所有的代码。 (代码是愚蠢的,只有不正是你告诉它!)

太行

print 'the phone number is: ',phoneNumbers 

将始终打印所有的电话号码。现在

为funsies,你可以试试:

print 'the phone number is: ',phoneNumbers[0] 

而且你会发现,第一个(或零索引)项目在您的手机号码清单打印出来。 (您可以将0-6中的任何数字放在那里,然后逐个获取所有电话号码)。

现在为您的家庭作业,你关心的是打印与名称相匹配的电话号码,而不仅仅是第一个。我们假设您的姓名与电话号码有一对一的映射关系。所以zeroeth phoneNumber匹配'todd',第一个phoneNumber匹配到'david'等等。如果您在列表中找到一个名字,说你正在寻找“安吉拉”,然后的代码行,上面写着:

if people[index] == searchValue: 

,当你到“安吉拉”,那么指数在那个时候将等于'2'。 (也许暂时在该行之后放置一个'打印索引'来说服你自己)。

现在,如果您打印phoneNumbers [2]或phoneNumbers [index],它将打印与'angela'匹配的数字。