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
To break out of a for loop, you can use the endloop, continue, resume, or return statement.
In most cases (including this one), return will exit immediately.
Yes, usually (and in your case) it does break out of the loop and returns from the method.
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.
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)
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With