Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming Loops in Python

Tags:

I recently read this question which had a solution about labeling loops in Java.

I am wondering if such a loop-naming system exists in Python. I have been in a situation multiple times where I do need to break out of an outer for loop from an inner for loop. Usually, I solve this problem by putting the inner loop in a function that returns (among others) a boolean which is used as a breaking condition. But labeling loops for breaking seems a lot simpler and I would like to try that, if such functionality exists in python

Does anyone know if it does?

like image 658
inspectorG4dget Avatar asked Dec 07 '11 17:12

inspectorG4dget


People also ask

Can you label loops in Python?

Many popular programming languages support a labelled break statement. It's mostly used to break out of the outer loop in case of nested loops. However, Python doesn't support labeled break statement. PEP 3136 was raised to add label support to break statement.

What are the 3 types of loops?

In Java, there are three kinds of loops which are – the for loop, the while loop, and the do-while loop. All these three loop constructs of Java executes a set of repeated statements as long as a specified condition remains true. This particular condition is generally known as loop control.


1 Answers

Here's a way to break out of multiple, nested blocks using a context manager:

import contextlib  @contextlib.contextmanager def escapable():     class Escape(RuntimeError): pass     class Unblock(object):         def escape(self):             raise Escape()      try:         yield Unblock()     except Escape:         pass 

You can use it to break out of multiple loops:

with escapable() as a:     for i in xrange(30):         for j in xrange(30):             if i * j > 6:                 a.escape() 

And you can even nest them:

with escapable() as a:     for i in xrange(30):         with escapable() as b:             for j in xrange(30):                 if i * j == 12:                     b.escape()  # Break partway out                 if i * j == 40:                     a.escape()  # Break all the way out 
like image 106
Stu Gla Avatar answered Nov 15 '22 12:11

Stu Gla