breaking out of outer loops

Chris Kaynor ckaynor at zindagigames.com
Mon Mar 7 18:42:48 EST 2016


On Mon, Mar 7, 2016 at 3:21 PM, Fillmore <fillmore_remove at hotmail.com>
wrote:

> On 3/7/2016 6:17 PM, Ian Kelly wrote:
>
>> On Mon, Mar 7, 2016 at 4:09 PM, Fillmore <fillmore_remove at hotmail.com>
>> wrote:
>>
>>>
>>> I must be missing something simple because I can't find a way to break
>>> out
>>> of a nested loop in Python.
>>>
>>> Is there a way to label loops?
>>>
>>
>> No, you can't break out of nested loops,
>>
>
> wow...this is a bit of a WTF moment to me :(
>
> apart from structuring your
>> code such that return does what you want.
>>
>>
> Can you elaborate? apologies, but I'm new to python and trying to find my
> way out of perl....


The normal way of breaking out of some set of loops would be to structure
your code so that you have a function, and when you want to break out of
some of multiple loops, you can just call return.


As a very rough example:

def processFile(file):
    for line in file:
        section = line.split()
        for section in line:
            if sectionCorrupt:
                return # Stops processing the entire file, by exiting the
function, but keeps processing the list of files.

for file in files:
    processFile(file)




Alternatively, as you mention corrupted lines, perhaps raising an exception
would be the best approach.

And the same rough example, using an exception without a function:

for file in files:
    try:
        for line in file:
            section = line.split()
            for section in line:
                if sectionCorrupt:
                    raise Exception('Section corrupt') # You probably want
more details here, for possible manual repair. You could also have a custom
exception class for more control.
    except Exception as e:
        print('Failed to process the file {} with error {}.'.format(file,
str(e))) # Probably should also print the entire traceback to aid in
repairing errors, especially if they are due to a bug in the code, but this
is the rough idea.



More information about the Python-list mailing list