简体   繁体   中英

Execution for-loop in Python

def search_for_element(L, char):
    for i in L:
        if i == char:
            return True
        else:
            return False

When I run the function, it only outputs one statement on the screen. So why is the for loop only executed once?

return terminates the function, move return False to after the loop:

def search_for_element(L, char):
    for i in L:
        if i == char:
            return True
    return False

Or simply:

def search_for_element(L, char):
    return char in L

Although note the latter is not exactly equivalent, since it also tests identity (not just equality). This will only matter in rather unusual circumstance though, for example numpy.NAN == numpy.NAN is False but numpy.NAN in [numpy.NAN] is True .

So the one-liner alternative would be:

def search_for_element(L, char):
    return any(char == i for i in L)

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