4

What's the best way to break from inner loop so I reach beginning of the outer loop

while condition:
    while second_condition:
        if some_condition_here:
            get_to_the_beginning_of_first_loop

Right now I got something like

while condition:
    while second_condition:
        if condition1:
            break
    if condition1:
        continue

2 Answers 2

7

Python has the option of an else: clause for while loops. This is called if you do not call break, so these are equivalent:

while condition:
    while second_condition:
        if condition1:
            break
    if condition1:
        continue
    do_something_if_no_break()

and:

while condition:
    while second_condition:
        if condition1:
            break
    else:
        do_something_if_no_break()
Sign up to request clarification or add additional context in comments.

5 Comments

Woah. Thats first am hearing about this.
@KaushikNP A more normal use is like for x in mylist: if x==5: break else: print("No five found!")
Nice. Good example.
condition1 uses some variable defined inside of second block what to do in this case.?
@Poojan If you use the else trick in my answer then you only need condition1 inside the second block, so I don't see the problem.
0

Just to build on @ArthurTacca's answer, you use Python's else operator to make an elegant, arbitrary-depth break capability:

# Copied from ArthurTacca
while condition:
    while second_condition:
        if condition1:
            break
    else:
        do_something_if_no_break()
        # Minor addition
        continue  # This avoids the break below
    break  # Fires if the inner loop hit a "break"

Note that this else:continue/break pattern can be repeated to an arbitrary depth, and works for for loops too.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.