Return Statement in for Loops

return in for loop or outside loop

Now someone told me that this is not very good programming because I use the return statement inside a loop and this would cause garbage collection to malfunction.

That's incorrect, and suggests you should treat other advice from that person with a degree of skepticism.

The mantra of "only have one return statement" (or more generally, only one exit point) is important in languages where you have to manage all resources yourself - that way you can make sure you put all your cleanup code in one place.

It's much less useful in Java: as soon as you know that you should return (and what the return value should be), just return. That way it's simpler to read - you don't have to take in any of the rest of the method to work out what else is going to happen (other than finally blocks).

How can I use `return` to get back multiple values from a loop? Can I put them in a list?

Using a return inside of a loop will break it and exit the function even if the iteration is still not finished.

For example:

def num():
# Here there will be only one iteration
# For number == 1 => 1 % 2 = 1
# So, break the loop and return the number
for number in range(1, 10):
if number % 2:
return number
>>> num()
1

In some cases we need to break the loop if some conditions are met. However, in your current code, breaking the loop before finishing it is unintentional.

Instead of that, you can use a different approach:

Yielding your data

def show_todo():
# Create a generator
for key, value in cal.items():
yield value[0], key

You can call it like:

a = list(show_todo())  # or tuple(show_todo())

or you can iterate through it:

for v, k in show_todo(): ...

Putting your data into a list or other container

Append your data to a list, then return it after the end of your loop:

def show_todo():
my_list = []
for key, value in cal.items():
my_list.append((value[0], key))
return my_list

Or use a list comprehension:

def show_todo():
return [(value[0], key) for key, value in cal.items()]

Does return stop a loop?

Yes, function's always end when ever there control flow meets a return statement.

The following example demonstrates how return statements end a function's execution.

function returnMe() {
for (var i = 0; i < 2; i++) {
if (i === 1) return i;
}
}

console.log(returnMe());

Why can't I write a return statement inside a loop?

In your initial code:

if (div == 1) {
return number;
} else {
number = div;
num = 1;
}
}

In case when you'll always have false, you will never reach return statement.
Compiler does not predict if it will actually happen so it requires return statements in both if and else blocks. So it actually has nothing to do with for loop.



Related Topics



Leave a reply



Submit