Gulzar
Gulzar

Reputation: 27966

How to continue a loop from within a function?

Consider the following

for i in range(100):
    if cond1:
        cleanup()
        continue
    if cond2:
        cleanup()
        continue
    if cond3:
        cleanup()
        continue
    ...

    do_work()

I was wondering if there is a way to write this construct in a more concise way, such that at least there won't be the cleanup(); continue duplicated fragment.

It is almost like I want a goto inside the cleanup to just go back to the top of the loop, or to push the continue into the cleanup function.

Is there a way to do something like that?


EDIT with a more elaborate example:

for i in range(100):
    if a == 1:
        cleanup()
        continue
    b = input()
    if a + b == 2:
        cleanup()
        continue
    c = input()
    if a + b + c:
        cleanup()
        continue
    ...

    do_work()

You will notice I want each condition to stop or continue iteration, which can't be done with or. Even if it can, this makes reading the code much simpler and linear.

Upvotes: 0

Views: 63

Answers (2)

chepner
chepner

Reputation: 531335

No; you can only control the loop from directly in the loop. cleanup cannot assume it will be called from a loop, so indirect breaks and continues are not allowed.

At least for the code shown, you can combine the various if statements into one:

for i in range(100):
    if cond1 or cond2 or cond3:
        cleanup()
        continue
    do_work()

Otherwise, you need to examine the return value of cleanup to determine whether to continue the loop or not.

Upvotes: 1

Alain T.
Alain T.

Reputation: 42143

If your conditions are simple, just do one if cond1 or cond2 or cond3: but I'm guessing that the actual code is more complex than that.

Assuming your conditions are complex and/or involved some preparations that require those clean ups, you can enclose them in a one-iteration for-loop that you break when no conditions are met. This will allow you to centralize the cleanup()/continue in an else: statement

for i in range(100):
    for preconditions in [1]:
        ...
        if cond1: continue
        ...
        if cond2: continue
        ...
        if cond3: continue            
        break                # final break when no conditions are met
    else:
        cleanup()
        continue

    do_work()

Note that you could do something similar with a custom exception and enclosing the conditions in a try/except statement but that seemed a bit overkill so I didn't include it in the answer

Upvotes: 1

Related Questions