'Best way in python to check if a loop is not executed

The title might be misleading, so here is a better explanation.

Consider the following code:

def minimum_working_environment(r):
    trial=np.arange(0,6)[::-1]
    for i in range(len(trial)):
        if r>trial[i]:
            return i
    return len(trial)

We see that if r is smaller than the smallest element of trial, the if clause inside the loop is never executed. Therefore, the function never returns anything in the loop and returns something in the last line. If the if clause inside the loop is executed, return terminates the code, so the last line is never executed.

I want to implement something similar, but without return, i.e.,

def minimum_working_environment(self,r):
    self.trial=np.arange(0,6)[::-1]
    for i in range(len(self.trial)):
        if r>trial[i]:
            self.some_aspect=i
            break
    self.some_aspect=len(self.trial)

Here, break disrupts the loop but the function is not terminated.

The solutions I can think of are:

  • Replace break with return 0 and not check the return value of the function.
  • Use a flag variable.
  • Expand the self.trial array with a very small negative number, like -1e99.

First method looks good, I will probably implement it if I don't get any answer. The second one is very boring. The third one is not just boring but also might cause performance problems.

My questions are:

Is there a reserved word like return that would work in the way that I want, i.e., terminate the function?

If not, what is the best solution to this?

Thanks!



Solution 1:[1]

You can check that a for loop did not run into a break with else, which seems to be what you're after.

import numpy as np


def minimum_working_environment(r):
    trial = np.arange(0, 6)[::-1]
    for i in range(len(trial)):
        if r > trial[i]:
            return i
    return len(trial)


def alternative(r):
    trial = np.arange(0, 6)[::-1]
    for i in range(len(trial)):
        if r > trial[i]:
            break
    else:
        i = len(trial)
    return i


print(minimum_working_environment(3))
print(minimum_working_environment(-3))

print(alternative(3))
print(alternative(-3))

Result:

3
6
3
6

This works because the loop controlling variable i will still have the last value it had in the loop after the break and the else will only be executed if the break never executes.

However, if you just want to terminate a function, you should use return. The example I provided is mainly useful if you do indeed need to know if a loop completed fully (i.e. without breaking) or if it terminated early. It works for your example, which I assume was exactly that, just an example.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1