multiple breaks

Steve Holden steve at holdenweb.com
Thu Nov 13 10:41:47 EST 2008


Chris Rebert wrote:
> On Thu, Nov 13, 2008 at 2:07 AM, TP <Tribulations at paralleles.invalid> wrote:
>> Hi everybody,
>>
>> Several means to escape a nested loop are given here:
>>
>> http://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python
>>
>> According to this page, the best way is to modify the loop by affecting the
>> variables that are tested in the loops. Otherwise, use exception:
>>
>> "If, for some reason, the terminating conditions can't be worked out,
>> exceptions are a fall-back plan."
>>
>> In the following example, is this possible to affect the two iterators to
>> escape the two loops once one "j" has been printed:
>>
> 
> Non-exception alternative:
> 
> done = False
>> for i in range(5):
>>    for j in range(i):
>>       print j
>         done = True
>         break
>>       # I would type "break 2" in shell bash
>>       # In C, I would set j=i-1 and i=4
>>       # In Python, is this possible to affect the two iterators?
>     if done:
>         break
>> Or the only means is to use exception?
> 
> No, you could add a boolean variable and a break condition like above.
> 
Though I would have to ask why you would want to. An exception seems
rather cleaner, though of course tastes vary.

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list