Python 谁能给我解释一下这个功能吗 我写了这个函数,但是。。。

Python 谁能给我解释一下这个功能吗 我写了这个函数,但是。。。,python,for-loop,Python,For Loop,当我传入该列表中的名称时,它返回该名称的索引,但当我传入错误的名称时,它返回-1,并且不返回“return(index)”,即使“return(index)”语句不在for循环中,为什么??而且我不能在“else”语句中添加任何其他内容,我试图在“else”语句中添加一个“print”语句,但它没有打印它 names=['neno', 'jay', 'james,'alex','adam','robert','geen'] name_index=look_up(names,"geen

当我传入该列表中的名称时,它返回该名称的索引,但当我传入错误的名称时,它返回-1,并且不返回“return(index)”,即使“return(index)”语句不在for循环中,为什么??而且我不能在“else”语句中添加任何其他内容,我试图在“else”语句中添加一个“print”语句,但它没有打印它

names=['neno', 'jay', 'james,'alex','adam','robert','geen']

name_index=look_up(names,"geen")

print(name_index)


print("the name is at location: {}".format(name_index))
但是,您可以找到具有
名称的函数索引。索引(“名称”)
有关更多信息,您可以实现以下函数:

def look_up_new(search_in, search_this):
    if search_this in search_in:
        return search_in.index(search_this) # returns index of the string if exist
    else:
        print("NOT EXIST") # you can print this line in else block also where I have written False
        return False

names=['neno', 'jay', 'james','alex','adam','robert','geen']

name_index = look_up_new(names, "alex")

if name_index:
    print("the name is at location: {}".format(name_index))
else:
    pass # if you are not willing to doing anything at here you can avoid this loop

'james
应该是
'james'
对吗?您编写了一个函数,但不了解它的功能?您是否尝试过使用调试器或纸笔单步执行代码?请澄清您的目标和问题我的问题是,如果您给函数传递了一个错误的名称,那么底部的“return(index)”语句不会运行,为什么它在for循环之外??
def look_up(to_search,target):
    for (index , item) in enumerate(to_search):
        if item == target:
             break # break statement here will break flow of for loop 
        else:
            return(-1)  # when you write return statement in function function will not execute any line after it

    return(index)
    print("This line never be printed")  # this line is below return statement which will never execute
def look_up_new(search_in, search_this):
    if search_this in search_in:
        return search_in.index(search_this) # returns index of the string if exist
    else:
        print("NOT EXIST") # you can print this line in else block also where I have written False
        return False

names=['neno', 'jay', 'james','alex','adam','robert','geen']

name_index = look_up_new(names, "alex")

if name_index:
    print("the name is at location: {}".format(name_index))
else:
    pass # if you are not willing to doing anything at here you can avoid this loop