Rushy Panchal
Rushy Panchal

Reputation: 17532

Python "While" Loops and Breaking Them

If I have two while: loops, one inside of the other, like such:

while #test :
    while #test :
        #other code
        if #test :
           break
    #other code

Will the break stop both while: loops or only the one where the if #test : is in?

Thanks for the help!

Upvotes: 1

Views: 210

Answers (4)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

From python documentation:

break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop.

It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.

"break terminates the nearest eclosing loop" - e.g. only inner while

Upvotes: 1

xxg1413
xxg1413

Reputation: 1

break only stop the one where the if #test,so the other code will be exec.

Upvotes: 0

Sufian Latif
Sufian Latif

Reputation: 13356

A break always breaks only the loop enclosing it, so the last line of the code will be executed under the outer loop.

Learn more

Upvotes: 3

Makoto
Makoto

Reputation: 106389

It would only stop the inner loop. If you wanted to break both loops, you'd have to provide another condition to break in the outer loop.

Upvotes: 6

Related Questions