Is it possible to a "continue" statement inside a function that gets called within a "for loop"?

Viewed 102

I have a for loop that I'm needing to break if there is an error.

I want to be able to continue a for loop if a boolean is true. But don't want to have to write an "if" statement over and over again. Is it possible to call "continue" outside of a "loop"?

The following code results in an error. But is my thinking of this would work.

_Range = 6
_RangeEnd = 0

def function_to_call():
    print("x")
    if _Continue is True:
        continue

for x in range(_Range):
    _RangeEnd = _RangeEnd + 1
    function_to_call()
    if _RangeEnd == 5:
        _Continue = True

If this isn't possible. What would be an efficient way to do this? I'm reusing this function in a good number of different for loops.

3 Answers

While I am in doubt this is a good idea for the flow control of the program, something like this can simulate what you need:

_Range = 6
_RangeEnd = 0

class Continue(Exception):
    pass

def function_to_call():
    print("x")
    if _Continue is True:
        raise Continue

for x in ...:
    try:
        function_to_call()
        something_else()
    except Continue:
        continue

And no, continue can't be outside the loop.

The continue needs to be inside a loop, I think the best solution would be to put a (if boolVar == True: continue) inside the for.

You can't call continue outside of a loop, e.g. from a function called from inside a loop.

One option is to return a meaningful value from your function that tells the caller to continue, i.e. some truthy value or falsy value:

CONTINUE = object()  # just some sentinel object, could use a proper class too, to be type-correct

def function_that_decides_to_continue():
    print("x")
    return your_condition_here

for x in range(_Range):
    if function_that_decides_to_continue():
        continue

Another option in an error-handling use-case is directly handling those exceptions with try/except:

def function_that_may_fail(divisor):
    return 10 / divisor

for x in [2, 5, 0, 1]:
    try:
        result = function_that_may_fail(x)
    except ZeroDivisionError:
        continue

    do_stuff_with(result)

Though I admit I might be misinterpreting what you actually want to do, because "want to be able to continue a for loop if a boolean is true" means a plain while:

while function_that_decides_to_continue():
    # do stuff

Or maybe just an if continue:

for x in range(_Range):
    # do stuff
    if function_that_decides_to_continue():
        continue  # skip extra stuff
    # do extra stuff

You'll have to provide actual examples of the "different for loops" you wanted your "function that continues" will be used in.

Related