电话号码查询程序

1 投票
4 回答
3181 浏览
提问于 2025-04-17 04:31

我在做数组作业时遇到了问题,我需要输入一个名字,然后程序应该返回这个名字的编号,但我现在得到的结果是返回了所有的编号。

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()

4 个回答

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

会一直打印出所有的电话号码。

现在为了好玩,试试这样的代码:

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

你会发现列表中的第一个(也就是索引为0的)电话号码会被打印出来。(你可以在这里放入0到6之间的任何数字,逐个获取所有电话号码)。

现在,作为你的作业,你需要打印出与名字匹配的电话号码,而不是仅仅打印第一个。我们假设每个名字都有对应的电话号码。所以,索引为0的电话号码对应'todd',索引为1的电话号码对应'david',依此类推。如果你在列表中找到了一个名字,比如说你在找'angela',那么这行代码:

    if people[index] == searchValue:

当你找到'angela'时,此时的索引值将等于'2'。(你可以暂时在那行代码后面加一个'print index',这样可以让你确认这一点)。

所以现在,如果你打印phoneNumbers[2]或者phoneNumbers[index],就会打印出与'angela'匹配的电话号码。

3

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

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

撰写回答