谁能向我解释这个功能

时间:2017-07-11 05:20:52

标签: python for-loop

我写了这个函数但是......

def look_up(to_search,target):
    for (index , item) in enumerate(to_search):
        if item == target:
             break

    else:
        return(-1)
    return(index)

当我在该列表中传入一个名称时,它返回该名称的索引,但是当我传入错误的名称时,它返回-1并且不返回" return(索引)"即使是"返回(索引)"语句不在for循环中为什么会这样?而且我也无法在" 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))

1 个答案:

答案 0 :(得分:1)

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

但是你可以找到names.index("NAME")的函数索引,你可以实现以下功能:

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