Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #104265 > unrolled thread

breaking out of outer loops

Started byFillmore <fillmore_remove@hotmail.com>
First post2016-03-07 18:09 -0500
Last post2016-03-08 03:45 +0000
Articles 15 — 8 participants

Back to article view | Back to comp.lang.python


Contents

  breaking out of outer loops Fillmore <fillmore_remove@hotmail.com> - 2016-03-07 18:09 -0500
    Re: breaking out of outer loops Ian Kelly <ian.g.kelly@gmail.com> - 2016-03-07 16:17 -0700
      Re: breaking out of outer loops Fillmore <fillmore_remove@hotmail.com> - 2016-03-07 18:21 -0500
        Re: breaking out of outer loops Chris Kaynor <ckaynor@zindagigames.com> - 2016-03-07 15:42 -0800
        Re: breaking out of outer loops Chris Angelico <rosuav@gmail.com> - 2016-03-08 10:49 +1100
        Re: breaking out of outer loops Terry Reedy <tjreedy@udel.edu> - 2016-03-07 21:54 -0500
    Re: breaking out of outer loops Rob Gaddi <rgaddi@highlandtechnology.invalid> - 2016-03-07 23:29 +0000
      Re: breaking out of outer loops Fillmore <fillmore_remove@hotmail.com> - 2016-03-07 18:40 -0500
    Re: breaking out of outer loops Chris Angelico <rosuav@gmail.com> - 2016-03-08 10:47 +1100
    Re: breaking out of outer loops Fillmore <fillmore_remove@hotmail.com> - 2016-03-07 19:02 -0500
      Re: breaking out of outer loops Chris Angelico <rosuav@gmail.com> - 2016-03-08 11:08 +1100
        Re: breaking out of outer loops Fillmore <fillmore_remove@hotmail.com> - 2016-03-07 19:13 -0500
          Re: breaking out of outer loops Joel Goldstick <joel.goldstick@gmail.com> - 2016-03-07 19:21 -0500
    Re: breaking out of outer loops Mark Lawrence <breamoreboy@yahoo.co.uk> - 2016-03-08 00:36 +0000
    Re: breaking out of outer loops Mark Lawrence <breamoreboy@yahoo.co.uk> - 2016-03-08 03:45 +0000

#104265 — breaking out of outer loops

FromFillmore <fillmore_remove@hotmail.com>
Date2016-03-07 18:09 -0500
Subjectbreaking out of outer loops
Message-ID<nbl1md$1lvd$1@gioia.aioe.org>
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?

For the record, here's a Perl script of mine I'm trying to port...there 
may be 'malformed' lines in a TSV file I'm parsing that are better 
discarded than fixed.

my $ctr = 0;
OUTER:
while($line = <FILE>) {

     $ctr++;
     if ($ctr < 5) {next;}

     my @allVals  = split /\t/,$line;

     my $newline;
     foreach my $i (0..$#allVals) {

	if ($i == 0) {
	    if ($allVals[0] =~ /[^[:print:]]/) {next OUTER;}

	    $newline =  $allVals[0];
	}

	if (defined $headers{$i}) {

	    #if column not a number, skip line
	    if ($allVals[$i+1] !~ /^\d+$/) {next OUTER;}

	    $newline .= "\t".$allVals[$i+1];
	}
     }
     print $newline."\n";

}

[toc] | [next] | [standalone]


#104268

FromIan Kelly <ian.g.kelly@gmail.com>
Date2016-03-07 16:17 -0700
Message-ID<mailman.1.1457392715.15725.python-list@python.org>
In reply to#104265
On Mon, Mar 7, 2016 at 4:09 PM, Fillmore <fillmore_remove@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, apart from structuring your
code such that return does what you want.

[toc] | [prev] | [next] | [standalone]


#104270

FromFillmore <fillmore_remove@hotmail.com>
Date2016-03-07 18:21 -0500
Message-ID<nbl2dd$1mkn$1@gioia.aioe.org>
In reply to#104268
On 3/7/2016 6:17 PM, Ian Kelly wrote:
> On Mon, Mar 7, 2016 at 4:09 PM, Fillmore <fillmore_remove@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....

[toc] | [prev] | [next] | [standalone]


#104274

FromChris Kaynor <ckaynor@zindagigames.com>
Date2016-03-07 15:42 -0800
Message-ID<mailman.4.1457394191.15725.python-list@python.org>
In reply to#104270
On Mon, Mar 7, 2016 at 3:21 PM, Fillmore <fillmore_remove@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@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.

[toc] | [prev] | [next] | [standalone]


#104276

FromChris Angelico <rosuav@gmail.com>
Date2016-03-08 10:49 +1100
Message-ID<mailman.6.1457394568.15725.python-list@python.org>
In reply to#104270
On Tue, Mar 8, 2016 at 10:42 AM, Chris Kaynor <ckaynor@zindagigames.com> wrote:
> 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.

Yes, although I would more strongly suggest the custom exception
class. In fact, the way I'd word it is: Never raise Exception, always
a subclass. Otherwise it's too easy to accidentally catch something
elsewhere in the code (a ValueError or TypeError or even
AttributeError).

ChrisA

[toc] | [prev] | [next] | [standalone]


#104318

FromTerry Reedy <tjreedy@udel.edu>
Date2016-03-07 21:54 -0500
Message-ID<mailman.31.1457405705.15725.python-list@python.org>
In reply to#104270
On 3/7/2016 6:49 PM, Chris Angelico wrote:
> On Tue, Mar 8, 2016 at 10:42 AM, Chris Kaynor <ckaynor@zindagigames.com> wrote:
>> 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.
>
> Yes, although I would more strongly suggest the custom exception
> class. In fact, the way I'd word it is: Never raise Exception, always
> a subclass. Otherwise it's too easy to accidentally catch something
> elsewhere in the code (a ValueError or TypeError or even
> AttributeError).

I would consider raising and catching StopIteration.

-- 
Terry Jan Reedy

[toc] | [prev] | [next] | [standalone]


#104271

FromRob Gaddi <rgaddi@highlandtechnology.invalid>
Date2016-03-07 23:29 +0000
Message-ID<nbl2rt$2hb$1@dont-email.me>
In reply to#104265
Fillmore 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?
>
> For the record, here's a Perl script of mine I'm trying to port...there 
> may be 'malformed' lines in a TSV file I'm parsing that are better 
> discarded than fixed.
>
> my $ctr = 0;
> OUTER:
> while($line = <FILE>) {
>
>      $ctr++;
>      if ($ctr < 5) {next;}
>
>      my @allVals  = split /\t/,$line;
>
>      my $newline;
>      foreach my $i (0..$#allVals) {
>
> 	if ($i == 0) {
> 	    if ($allVals[0] =~ /[^[:print:]]/) {next OUTER;}
>
> 	    $newline =  $allVals[0];
> 	}
>
> 	if (defined $headers{$i}) {
>
> 	    #if column not a number, skip line
> 	    if ($allVals[$i+1] !~ /^\d+$/) {next OUTER;}
>
> 	    $newline .= "\t".$allVals[$i+1];
> 	}
>      }
>      print $newline."\n";
>
> }

You're used to Perl, you're used to exceptions being A Thing.  This is
Python, and exceptions are just another means of flow control.

class MalformedLineError(Exception): pass

for line in file:
    try:
        for part in line.split('\t'):
            if thispartisbadforsomereason:
                raise MalformedLineError()
            otherwisewedothestuff
    except MalformedLineError:
        pass

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com

Email address domain is currently out of order.  See above to fix.

[toc] | [prev] | [next] | [standalone]


#104272

FromFillmore <fillmore_remove@hotmail.com>
Date2016-03-07 18:40 -0500
Message-ID<nbl3gj$gkg$1@gioia.aioe.org>
In reply to#104271
On 3/7/2016 6:29 PM, Rob Gaddi wrote:
>
> You're used to Perl, you're used to exceptions being A Thing.  This is
> Python, and exceptions are just another means of flow control.
>
> class MalformedLineError(Exception): pass
>
> for line in file:
>      try:
>          for part in line.split('\t'):
>              if thispartisbadforsomereason:
>                  raise MalformedLineError()
>              otherwisewedothestuff
>      except MalformedLineError:
>          pass
>

I am sure you are right, but adapting this thing here into something 
that is a fix to my problem seems like abusing my 'system 2' (for those 
who read a certain book by a guy called Daniel Kanheman :)

[toc] | [prev] | [next] | [standalone]


#104275

FromChris Angelico <rosuav@gmail.com>
Date2016-03-08 10:47 +1100
Message-ID<mailman.5.1457394438.15725.python-list@python.org>
In reply to#104265
On Tue, Mar 8, 2016 at 10:09 AM, Fillmore <fillmore_remove@hotmail.com> wrote:
> For the record, here's a Perl script of mine I'm trying to port...there may
> be 'malformed' lines in a TSV file I'm parsing that are better discarded
> than fixed.
>
> my $ctr = 0;
> OUTER:
> while($line = <FILE>) {
>
>     $ctr++;
>     if ($ctr < 5) {next;}
>
>     my @allVals  = split /\t/,$line;
>
>     my $newline;
>     foreach my $i (0..$#allVals) {
>
>         if ($i == 0) {
>             if ($allVals[0] =~ /[^[:print:]]/) {next OUTER;}
>
>             $newline =  $allVals[0];
>         }
>
>         if (defined $headers{$i}) {
>
>             #if column not a number, skip line
>             if ($allVals[$i+1] !~ /^\d+$/) {next OUTER;}
>
>             $newline .= "\t".$allVals[$i+1];
>         }
>     }
>     print $newline."\n";
>
> }

I'm not too fluent in Perl, but my understanding here is that "next
OUTER" is equivalent to Python's 'continue' statement, right? So your
flow control is roughly this:

for _ in range(5): skip header row
for line in file:
    for cell in split(line):
        if bad_cell_value:
            break # Skip out of the inner loop now
    else:
        print_stuff # We didn't break

Does that look right? The key here is that a 'for' loop has an 'else'
clause, which happens if there's no 'break' in the main loop. I think
that's what you're after, here; you get to break out of "the loop and
a little bit more", so to speak. The outer loop is actually immaterial
here.

ChrisA

[toc] | [prev] | [next] | [standalone]


#104277

FromFillmore <fillmore_remove@hotmail.com>
Date2016-03-07 19:02 -0500
Message-ID<nbl4qj$i5v$1@gioia.aioe.org>
In reply to#104265
On 3/7/2016 6:09 PM, Fillmore wrote:
>
> I must be missing something simple because I can't find a way to break
> out of a nested loop in Python.

Thanks to everyone who has tried to help so far. I suspect this may be a 
case where I just need to get my head around a new paradigm


[toc] | [prev] | [next] | [standalone]


#104279

FromChris Angelico <rosuav@gmail.com>
Date2016-03-08 11:08 +1100
Message-ID<mailman.8.1457395717.15725.python-list@python.org>
In reply to#104277
On Tue, Mar 8, 2016 at 11:02 AM, Fillmore <fillmore_remove@hotmail.com> wrote:
> On 3/7/2016 6:09 PM, Fillmore wrote:
>>
>>
>> I must be missing something simple because I can't find a way to break
>> out of a nested loop in Python.
>
>
> Thanks to everyone who has tried to help so far. I suspect this may be a
> case where I just need to get my head around a new paradigm

Yep, which is why we're offering a variety of new paradigms. Because
it's ever so much easier to get your head around three than one!

We are SO helpful, guys. So helpful. :)

ChrisA

[toc] | [prev] | [next] | [standalone]


#104281

FromFillmore <fillmore_remove@hotmail.com>
Date2016-03-07 19:13 -0500
Message-ID<nbl5fd$ivb$1@gioia.aioe.org>
In reply to#104279
On 3/7/2016 7:08 PM, Chris Angelico wrote:

>
> Yep, which is why we're offering a variety of new paradigms. Because
> it's ever so much easier to get your head around three than one!
>
> We are SO helpful, guys. So helpful. :)

not too dissimilarly from human languages, speaking a foreign language 
is more often than not a matter of learning to think differently...

[toc] | [prev] | [next] | [standalone]


#104282

FromJoel Goldstick <joel.goldstick@gmail.com>
Date2016-03-07 19:21 -0500
Message-ID<mailman.10.1457396500.15725.python-list@python.org>
In reply to#104281
On Mon, Mar 7, 2016 at 7:13 PM, Fillmore <fillmore_remove@hotmail.com>
wrote:

> On 3/7/2016 7:08 PM, Chris Angelico wrote:
>
>
>> Yep, which is why we're offering a variety of new paradigms. Because
>> it's ever so much easier to get your head around three than one!
>>
>> We are SO helpful, guys. So helpful. :)
>>
>
> not too dissimilarly from human languages, speaking a foreign language is
> more often than not a matter of learning to think differently...
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>

I found this on break and continue.  I don't know perl, but if what you
want to do is quit continuing in a loop and go to the next iteration, then
continue will do that.
http://www.tutorialspoint.com/python/python_loop_control.htm

-- 
Joel Goldstick
http://joelgoldstick.com/ <http://joelgoldstick.com/stats/birthdays>
http://cc-baseballstats.info/

[toc] | [prev] | [next] | [standalone]


#104284

FromMark Lawrence <breamoreboy@yahoo.co.uk>
Date2016-03-08 00:36 +0000
Message-ID<mailman.11.1457397446.15725.python-list@python.org>
In reply to#104265
On 07/03/2016 23:09, Fillmore 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?
>
> For the record, here's a Perl script of mine I'm trying to port...there
> may be 'malformed' lines in a TSV file I'm parsing that are better
> discarded than fixed.
>
> my $ctr = 0;
> OUTER:
> while($line = <FILE>) {
>
>      $ctr++;
>      if ($ctr < 5) {next;}
>
>      my @allVals  = split /\t/,$line;
>
>      my $newline;
>      foreach my $i (0..$#allVals) {
>
>      if ($i == 0) {
>          if ($allVals[0] =~ /[^[:print:]]/) {next OUTER;}
>
>          $newline =  $allVals[0];
>      }
>
>      if (defined $headers{$i}) {
>
>          #if column not a number, skip line
>          if ($allVals[$i+1] !~ /^\d+$/) {next OUTER;}
>
>          $newline .= "\t".$allVals[$i+1];
>      }
>      }
>      print $newline."\n";
>
> }

I suggest you read and digest the various responses here 
http://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python, 
some of which are similar if not identical to answers you've all ready 
been given.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

[toc] | [prev] | [next] | [standalone]


#104320

FromMark Lawrence <breamoreboy@yahoo.co.uk>
Date2016-03-08 03:45 +0000
Message-ID<mailman.33.1457408788.15725.python-list@python.org>
In reply to#104265
On 07/03/2016 23:09, Fillmore 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?
>
> For the record, here's a Perl script of mine I'm trying to port...there
> may be 'malformed' lines in a TSV file I'm parsing that are better
> discarded than fixed.
>

[snipped the code as I don't understand it]

Another interesting read that I've found 
http://nedbatchelder.com/blog/201203/breaking_out_of_two_loops_at_once.html

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web