顺序搜索数据库

时间:2014-10-30 23:45:00

标签: python loops search

以下是我遇到问题的一些代码的一部分:

def func():
    for i in range(len(titleList)):
        print titleList[i] + ' -- ' + artistList[i] + ' -- ' + albumList[i] + ' --',
        print yearList[i] + ' -- ' + commentList[i]

def sequentialSearch(albumList, item):
    pos = 0
    found = False
    while pos < len(albumList) and not found:
        if albumList[pos] == item:
            found = True
        else:
            pos = pos + 1
    return found

num = input("What would you like to do?\n1. Print all the contents of the database\n2. Find all the songs on a particular album\n3. Quit\nPlease Enter 1, 2, or 3: ")
if num == 3:
    print "Goodbye"
else:
    while num != 3:
        if num == 1:
            func()
        if num == 2:
            item = raw_input("Please enter the album: ")
            seqentialSearch(albumList, item)
        else:
            print "Invald Input"

我有一个数据库,该程序正在从中提取数据。我需要它表现得像这样:

  • 如果输入1,程序将返回数据库的全部内容
  • 如果输入2,我希望程序使用顺序搜索打印该相册中歌曲的所有信息
  • 如果输入3,我只想打印&#34;再见&#34;

我遇到的两个问题是:

  1. 我的顺序搜索代码未返回正确的信息
  2. 我希望程序循环直到输入3。
  3. 如何解决这些问题?

2 个答案:

答案 0 :(得分:0)

您的sequentialSearch功能不打印任何内容。并且您不需要found变量,当您找到匹配项时,您可以从该函数return获得。{/ p>

def sequentialSearch(albumList, item):
    for i in range(len(albumlist))
        if albumList[i] == item:
            print titleList[i] + ' -- ' + artistList[i] + ' -- ' + albumList[i] + ' --',
            print yearList[i] + ' -- ' + commentList[i]
            return true
    return false

在您的主代码中,您的while循环永远不会结束,因为您在循环外请求num。使用:

while true:
    num = input("What would you like to do?\n1. Print all the contents of the database\n2. Find all the songs on a particular album\n3. Quit\nPlease Enter 1, 2, or 3: ")
    if num == 3:
        print "Goodbye"
        break
    elif num == 1:
        func()
    elif num == 2:
        item = raw_input("Please enter the album: ")
        sequentialSearch(albumList, item)
    else:
        print "Invald Input"

答案 1 :(得分:0)

可以根据需要控制选项:

num = 0
while num !=3:
    num = input("What would you like to do?\n1. Print all the contents of the database\n2. Find all the songs on a particular album\n3. Quit\nPlease Enter 1, 2, or 3: ")
    if num == 1:
        func()
    elif num == 2:
        item = raw_input("Please enter the album: ")
        seqentialSearch(albumList, item)
    elif num != 3:
        print "Invald Input"
print "Goodbye"