0

For instance, if you have the following (random example):

w = input("Enter width")
h = input("Enter height")

for x in range(0,w):
    for y in range(0,h):
        print x,y
        if (raw_input("Stop? y/n") == "y"):
            break

That would only break out of the y loop. You could introduce another variable, and change the loop to more or less this form:

for x in range(0,w):
    for y in range(0,h):
        print x,y
        stop = raw_input("Stop? y/n")
        if stop == "y":
            break
    if stop == "y":
        break

But that's pretty ugly, and there are a few cases where it could get very complicated, and you'd need to introduce a flag. Instead, is there any way to tell the break to break out of two levels instead of just one?

3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by vegaseat
0

One way is to raise you own exception and then catch it with a break.

class myException(Exception): pass
w = input("Enter width")
h = input("Enter height")

for x in range(0,w):
    for y in range(0,h):
        print x,y
        if (raw_input("Stop? y/n") == "y"):
            raise myException
    except myException:
       break

any help?

Chris

0

Simply put the nested loop into a function and use return to break out ...

def exit_nested_loop():
    w = h = 100  # for testing
    for x in range(0, w):
        for y in range(0, h):
            print x, y
            stop = raw_input("Stop? y/n")
            if stop == "y":
                return

exit_nested_loop()

If you want to use try/except you can do it this way ...

w = h = 100  # for testing
try:
    for x in range(0, w):
        for y in range(0, h):
            print x, y
            if raw_input("Stop? y/n") == "y":
                raise StopIteration()
except StopIteration:
    pass

C used to have the much frowned upon goto statement for such a thing.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.