[Tutor] How many loops does "break" jump out of?

Alan Gauld alan.gauld at btinternet.com
Thu Feb 22 23:00:12 CET 2007

<etrade.griffiths at dsl.pipex.com> wrote 

> Am trying to convert a C program with a GOTO in it 
> to Python and was wondering how many loops a 
> Python "break" jumps out of.  

Just the immediately enclosing loop.
You can fake higher level breaks by setting 
a global variable and immediately after the 
exit from the inner loop check the value and 
if necessary break again.

brk_level = 0   # 1= all levels, 0 = just one

while 1:
    while 1:
        if test():
            brk_level = 1
    if brk_level > 0: break

But its nearly always possibly to just restructure the 
code to avoid the need for such tricks.

Alan G.

More information about the Tutor mailing list