Thread: Loops in Python
View Single Post
Old Jan 6th, 2007, 5:09 AM   #4
hydroxide
Programmer
 
Join Date: Apr 2005
Posts: 73
Rep Power: 4 hydroxide is on a distinguished road
Another way of breaking a while loop - or even nested while loops -- is to use a flag. If you find yourself using this technique, though, you probably need to redesign:
flag1 = False
flag2 = False
while not (flag1 or flag2):
    for i in range(10):
        print i
        if i == 4:
            flag1 = True
            break
        elif i == 6:
            flag2 = True
            break

A sometimes useful trick for getting out of nested loops is to raise an exception - StopIteration is the clearest, (use sparingly - a redesign/restructure is normally better):
def myfunc(i, j):
    print i, j
    if i == j == 1:
        raise StopIteration
    
try:
    while True:
        for i in range(10):
            for j in range(10):
                myfunc(i, j)
except StopIteration:
    pass
-T.
hydroxide is offline   Reply With Quote