简体   繁体   English

无论字符串是否在列表中,始终输出“不在列表中”

[英]Always outputs “is not in the list” no matter if the string is in the list or not

I cannot figure out why the output is always "is not in the list" even when I enter a string that is in the list.我无法弄清楚为什么 output 总是“不在列表中”,即使我输入了列表中的字符串。 I have checked if the variables are passing properly into the LinearSearch function and don't think it has anything to do with my syntax (though I may be wrong).我检查了变量是否正确传递到 LinearSearch function 并且认为它与我的语法没有任何关系(尽管我可能错了)。 New to programming and this is my first question on stackoverflow so don't be too harsh on me.编程新手,这是我关于 stackoverflow 的第一个问题,所以不要对我太苛刻。 :) :)

The Code:编码:

def main():
    NameList = []
    found = bool
    for Index in range(0, 4):
        NameList.append(str(input("Enter a name: ")))
    SearchName = input("Please enter the name you want to search for: ")
    found = LinearSearch(NameList, SearchName)
    if found == True:
        print(SearchName,"is in the list.")
    elif found == False:
        print(SearchName,"is not in the list.")

def LinearSearch(NameList, SearchName):
    for Index in range(0, 4):
        if SearchName == NameList[Index]:
            return True
        else:
            return False

main()

Your LinearSearch function is returning False if the first name in the list is not the name you're searching for.如果列表中的名字不是您要搜索的名称,您的LinearSearch function 将返回False You have to let it finish looping over the rest of the list, then return False if the name was never found.您必须让它完成对列表的 rest 的循环,如果从未找到该名称,则返回False

def LinearSearch(NameList, SearchName):
    for Index in range(0, 4):
        if SearchName == NameList[Index]:
            return True
    return False

One improvement you can make to your code is to search through the entire list no matter how long it is, instead of only looking at the first four indices:您可以对代码进行的一项改进是搜索整个列表,无论它有多长,而不是只查看前四个索引:

def LinearSearch(NameList, SearchName):
    for name in NameList:
        if SearchName == name:
            return True
    return False

(I don't know if the point of the exercise was to write LinearSearch , but that can be significantly shortened using Python's in operator instead.) (我不知道练习的重点是否是编写LinearSearch ,但是使用 Python 的in运算符可以显着缩短它。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM