Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning out of for-loop

I'm pretty new at python and I was wondering if this:

def func(self, foo):
    for foo in self.list:
        if foo.boolfunc(): return True
    return False

is good practice.

Can I return out of a loop like the above or should i use a while-loop, like so?

def func(self, foo):  
    found = false
    while(not found & i < len(self.list)):
        found = foo.boolfunc()
        ++i
    return found

My java-professor warns us never to use breaks in our loops, but this technically isn't a break and it's more concise, so... yeah

thanks

like image 919
thepandaatemyface Avatar asked Mar 02 '10 14:03

thepandaatemyface


People also ask

How do I return from a for loop?

To break out of a for loop, you can use the endloop, continue, resume, or return statement.

Does return exit a for loop?

In most cases (including this one), return will exit immediately.

Can we return from for loop in Java?

Yes, usually (and in your case) it does break out of the loop and returns from the method.

How do you get out of for loop if condition is met?

In situations where we want to stop the iteration before getting to the last item or before a given condition is met, we can use the break statement. The break statement will have its own condition – this tells it when to "break" the loop.


3 Answers

There's nothing wrong with your example, but it's better to write

def func(self, foo):
    return any(foo.boolfunc() for foo in self.list)
like image 171
John La Rooy Avatar answered Oct 16 '22 17:10

John La Rooy


It should be mentioned that in Python, for loops can have an else clause. The else clause is only executed when the loop terminates through exhaustion of the list.

So you could write:

def func(self):
    for foo in self.list:
        if foo.boolfunc():
            return True
    else:
        return False
like image 41
codeape Avatar answered Oct 16 '22 16:10

codeape


Your professor is advocating a practice called "Single point of Return", which basically states that any block of code should only have one point of exit. Breaks in loops are somewhat distinct from this, but usually lumped together.

It's a controversial opinion, to say the least, and certainly not as hard and fast a rule as "never use goto". It's probably worth doing it his way - you can appease him and also see the benefit of both approaches, but most people probably aren't too strict on single point of return if violating it makes their code more readable.

like image 44
Ryan Brunner Avatar answered Oct 16 '22 17:10

Ryan Brunner