for and while with else

#search target in list , while done the loop, and not happen break, it will do else
#in this function, while done the loop,mean it can't found the target,so it set index to -1
#and return the index
#else is a choice,not necessary
def list_find_while(lst, target):
    index = 0
    while(index < len(lst)):
        if(lst[index] == target):
            break
        index += 1
    else:
        index = -1
    return index
#search target in list , for done the loop, and not happen break, it will do else statement
#in this function, for done the loop,mean it can't found the target,so it set index to -1
#and return the index
#else is a choice,not necessary
#in for loop enumerate will return a index and the value
'''
enumerate(list, start=0) it can set the index where start
example for enumerate
for index, x in enumerate(['a','b','c','d']):
    print(index, x)
will output
0 'a'
1 'b'
2 'c'
3 'd'
'''
def list_find_for(lst, target):
    for index, x in enumerate(lst) :
        if(lst[index] == target):
            break
    else:
        index = -1
    return index

testlst = [1,2,3,4,5]
print(list_find_while(testlst, 3), list_find_for(testlst, 2))

0 意見:

張貼留言