Y
Y
Yevgeni2018-08-26 02:18:08
Python
Yevgeni, 2018-08-26 02:18:08

How to forcibly block the execution of the while loop and all the loops that are inside it?

while turned_on:
sub_loop
How, when the variable turned_on is changed to True, block the execution of the while loop and all previously running loops inside it without waiting for the code to complete execution.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nikita, 2018-08-26
@vasilek-nik

For example with exceptions:

class BreakIt(Exception): pass

try:
    for x in range(10):
        for y in range(10):
            print x*y
            if x*y > 50:
                raise BreakIt
except BreakIt:
    pass

There are two nested for'a here, although the type of loop is not critical. When you need to exit all, an exception is thrown, which is caught after the loop.
Just do not say that this is not your case and you need to exit by changing the value of the variable. This example can be easily adapted to your case.

L
lega, 2018-08-26
@lega

return if within the same function, otherwise raise

J
Jock Tanner, 2018-08-26
@Tanner

Put the outer while in the function; do a return to stop all loops.
Controlling execution through an exception is also valid in Python, but return is more readable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question