数据库的顺序搜索

2024-10-03 13:26:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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,我只想打印“再见”

我有两个问题:

  1. 我的顺序搜索码没有返回正确的信息
  2. 我希望程序循环直到输入3。你知道吗

如何解决这些问题?你知道吗


Tags: thepos程序lenifdefitemelse
2条回答

类似这样的操作可以根据需要控制选项:

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"

您的sequentialSearch函数没有打印任何内容。您不需要found变量,只要在找到匹配项时从函数中return。你知道吗

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"

相关问题 更多 >