Skip to content Skip to sidebar Skip to footer

How To Break A Loop From An Outside Function

My question is how can you break from outside a loop. If i can't is there a work around? def breaker(numberOfTimesYouWantToBreak): for i in range(0,numberOfTimesYouWantToBreak+

Solution 1:

You cannot use the break statement anywhere else but directly in the loop. You cannot return it from another function, it is not an object to be passed around.

You appear to want to skip, not break from the loop, however. You are looking for the continue keyword instead:

for i in range(0,100000):
    if i < 10:
        continueprint(i)

If you must use a separate function, then have that function return True or False and use an if test to conditionally use continue:

def should_skip(i):
    return i < 10for i in range(0,100000):
    ifshould_skip(i):
        continueprint(i)

Solution 2:

It's impossible.

The workaround is to put your code into a function and return from the function.

Solution 3:

You can't break externally, however, for the same effect you can do this:

for i inrange(0,100000):
    i += 10 + 1#(10 is the number you wanted in the break function)print(i)

Post a Comment for "How To Break A Loop From An Outside Function"