使用用户输入搜索编号列表并打印结果



我遇到了另一个与类相关的问题。我不是在寻找答案,更多的只是一个前进的方向。

对于这个项目,我需要用用户输入搜索一个列表,并让它打印结果。例如,如果您要在列表中搜索名称";Gabriel";,它将打印";Gabriel在流行名字列表中排名第5;。到目前为止,我只打印了"____"未被排名";

    boyNames = open('boyNames.txt', 'r')
boyNamesList = boyNames.read().split('n')
boyNames.close()
 
for i, j in enumerate(boyNamesList, 1):
        userName = input('Enter a name: ')
        if j == userName:
            print(userName, 'is ranked #', i , 'in the list of popular names.')
        else:
            print(userName, 'is not ranked.')
           

您需要将输入移动到for循环之外:

userName = input('Enter a name: ')
for i, j in enumerate(boyNamesList, 1):
    if j == userName:
        print(userName, 'is ranked #', i , 'in the list of popular names.')
        break
else:
    print(userName, 'is not ranked.')

原始代码在每次迭代中都要求输入,并且只检查输入的名称是否与当前迭代中的名称匹配。

你的逻辑也不正确,因为你不能说一个名字";未被排名";只需将userName与当前迭代中的名称进行核对;在得出结论之前,您需要先检查整个列表,因此需要使用for-else循环。

上面代码中的问题是,在搜索名称的循环中,您要求输入。为了修复,将输入移动到循环之前。此外,我已更改为只在搜索列表后打印排名。

userName = input('Enter a name: ')
rank = None
for i, name in enumerate(boyNamesList, 1):
    if name == userName:
        rank = i
if rank:
    print(userName, 'is ranked #', i , 'in the list of popular names.')
else:
    print(userName, 'is not ranked.')

最新更新