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?

Recommended Answers

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 …

Jump to Post

All 2 Replies

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.