简体   繁体   中英

question about the find() function in python

I am a newbie to python. During an exercise I tried to run the following code:

def my_find(haystack,needle):
    for index,letter in enumerate(haystack):
        if letter==needle:
            return index
        return -1
print(my_find("banana","a"))

The result is -1, which is not what I expected. How can I make it work properly?

please return the value outside for loop

def my_find(haystack,needle):
    for index,letter in enumerate(haystack):
        if letter==needle:
            return index
    return -1
print(my_find("banana","a"))

And use this if you want to find all needles and get it returned as a list:

def my_find(haystack,needle):
    matches=[]
    for index,letter in enumerate(haystack):
        if letter==needle:
            matches.append(index)
    return matches

In the comments it was rightly pointed out that the second return statement was in the wrong place.

The correct code should be -

def my_find(haystack,needle):
    for index,letter in enumerate(haystack):
        if letter==needle:
            return index
    return -1
print(my_find("banana","a"))

return should be outside the "for" block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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