python3 - 学习搜索,这个非常简单的例子不能正常工作

Sam*_*ikh 0 python sorting search list python-3.x

这是代码:

def findsort(something, alist):
    for item in alist:
        if item == something:
            return "found"
        else:
            return "not found"

def main():

    print(findsort(6, [3, 6, 1, 8, 11, 14]))

main()
Run Code Online (Sandbox Code Playgroud)

出于某种原因,这不符合我认为它应该工作的方式.

当我运行它时,它会说"找不到".但是,如果我将要查找的值更改为列表中的第一项,即3,则返回"已找到".

我用字符串尝试了这个,我得到了相同的结果.

谁能告诉我我做错了什么?

Hyp*_*eus 5

因为如果在第一次迭代中项目不匹配,则进入else分支返回"not found",从而退出循环.

试试这个:

def findsort(something, alist):
    for item in alist:
        if item == something:
            return "found"
    return "not found"
Run Code Online (Sandbox Code Playgroud)

或者干脆:

def findsort(something, alist):
    return "found" if something in alist else "not found"
Run Code Online (Sandbox Code Playgroud)