1

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+1):
        return break
while True:
    for i in range(0,100000):
        breaker(10)
        print(i)

The result i want is:

11,12,13,14...
Steven Cox
  • 23
  • 4

3 Answers3

5

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:
        continue
    print(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 < 10

for i in range(0,100000):
    if should_skip(i):
        continue
    print(i)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

It's impossible.

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

wim
  • 338,267
  • 99
  • 616
  • 750
0

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

for i in range(0,100000):
    i += 10 + 1 #(10 is the number you wanted in the break function)
    print(i)
Blubberguy22
  • 1,344
  • 1
  • 17
  • 29