Loops Control with Python

hg hg at nospam.com
Fri Oct 13 12:13:31 EDT 2006


Paddy wrote:
> Wijaya Edward wrote:
>> Can we make loops control in Python?
>> What I mean is that whether we can control
>> which loops to exit/skip at the given scope.
>>
>> For example in Perl we can do something like:
>>
>> OUT:
>> foreach my $s1 ( 0 ...100) {
>>
>>     IN:
>>     foreach my $s2 (@array) {
>>
>>           if ($s1 == $s2) {
>>              next OUT;
>>           }
>>           else {
>>               last IN;
>>           }
>>
>>      }
>> }
>>
>> How can we implement that construct with Python?
>>
> 
> Python does not use Labels. If you want to quit a single loop then look
> up the Python break statement. If you want to exit deeply nested
> execution then Python has exceptions. this maybe new to a Perl
> programmer so please take time to understand Python exceptions.
> 
> There follows a function that you can call from an interactive session
> to explore one type of use for exceptions  that is rather like your use
> of Perl labels shown.
> 
> ==========================
> class Outer(Exception):
>   pass
> class Inner(Exception):
>   pass
> 
> def skip_loops(y1 = -1, y2 = -1, y3 = -1):
>   ''' Shows how to skip parts of nested loops in Python'''
>   try:
>     for x0 in range(3):
>       try:
>         for x1 in range(3):
>           for x2 in range(3):
>             if x2 == y2:
>               raise Inner
>             if x2 == y3:
>               break
>             print (x0,x1,x2)
>           if x1 == y1:
>             raise Outer
>           print (x0,x1)
>       except Inner:
>         print "Raised exception Inner"
>       print (x0,)
>   except Outer:
>     print "Raised exception Outer"
> 
> ==========================
> 
>>>> skip_loops(y1=2)
> (0, 0, 0)
> (0, 0, 1)
> (0, 0, 2)
> (0, 0)
> (0, 1, 0)
> (0, 1, 1)
> (0, 1, 2)
> (0, 1)
> (0, 2, 0)
> (0, 2, 1)
> (0, 2, 2)
> Raised exception Outer
>>>> skip_loops(y2=2)
> (0, 0, 0)
> (0, 0, 1)
> Raised exception Inner
> (0,)
> (1, 0, 0)
> (1, 0, 1)
> Raised exception Inner
> (1,)
> (2, 0, 0)
> (2, 0, 1)
> Raised exception Inner
> (2,)
> 
> 
> - Paddy.
> P.S. Welcome to Python!
> 
How about a thread on GOTOs ? ;-)




More information about the Python-list mailing list