buzsh
buzsh

Reputation: 133

Break outside of two loops

I'm writing a code with a while loop inside a while loop and am wondering how to break out of the outer loop if I meet the necessary conditions in the inner loop.

while N <= 8:
    while i < 60:
        if this:
            that
        elif this:
            that other thing
        else:
            break
        i += 1
    if while loop has found the right thing:
        N += 1
    else:
        change conditions

This break command will only break out of the first loop, so I'm wondering how to simply break out both. It might be worth mentioning that all this is in another for loop which I wouldn't want to break out of. Thank you.

Upvotes: 1

Views: 114

Answers (3)

Ashwani
Ashwani

Reputation: 2052

Use flag:

flag = True
while N <= 8:
    while i < 60:
        if this:
            that
        elif this:
            that other thing
        else:
            flag = False    # To exit from outer while loop
            break
        i += 1
    if(not flag):               
        break               # Condition in inner loop is met
    if while loop has found the right thing:
        N += 1
    else:
        change conditions

Upvotes: 1

Dinesh Panchananam
Dinesh Panchananam

Reputation: 694

Use a flag; trigger is used here

trigger = False
while N <= 8:
    while i < 60:
        if this:
            that
        elif this:
            that other thing
        else:
            trigger = True
            break
        i += 1
    if trigger:
        break
    elif while loop has found the right thing:
        N += 1
    else:
        change conditions

Upvotes: 2

&#193;lvaro G&#243;mez
&#193;lvaro G&#243;mez

Reputation: 306

Encapsulate it in a function and return when you are done?

Upvotes: 6

Related Questions