Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinguishing multiple exit points in loop

Tags:

python

loops

I was watching python lecture by Raymond Hettinger on youtube. And he showed the right way to exit for loop:

def find(seq, target):
    for i, value in enumerate(seq):
        if value == target:
            break
    else:
        return -1
    return i

I dont get why bother with else statement and not just do:

def find(seq, target):
    for i, value in enumerate(seq):
        if value == target:
            return i
    return -1

Am I missing something or it is just good idea to sometimes add this else/break statement for whatever reason?

like image 312
user8856277 Avatar asked Nov 05 '17 18:11

user8856277


1 Answers

Condensed answer: Once you use return you are out of your function. Break means the code continue to run and you can add more things. So you are right in your example, but what if you want to do more things if nothing was found:

Raise an error:

def find(seq, target):
    for i, value in enumerate(seq):
        if value == target:
            break
    else:
        raise ValueError("Nothing found in {}".format(seq))
    return i


find("hello","a")

Or write to a file:

def find(seq, target):
    for i, value in enumerate(seq):
        if value == target:
            break
    else:
        with open("output.txt", "w") as f:
            f.write("Nothing found :(((")
    return i


find("hello","a")

Developping further (@Joe Iddon):

You maybe want to continue further too:

def find(seq, target):
    for i, value in enumerate(seq):
        if value == target:
            break
    else:
        return "Nothing found"

    # calculate more things
    a = [1,2,3]
    if i in a:
        return i
    else:
        return "Not in a"


find("hello","a")

So for this small purpose it wasn't necessary. But if you are building something upon that, the else clause can be useful.

like image 125
Anton vBR Avatar answered Nov 15 '22 02:11

Anton vBR