-3

Can I break out of a nested while loop?

I have highlighted with yellow of what happens in my code. As can be seen, if the condition is true it breaks out and the first 'exit' line is executed.

Is there a way I can exit the last exit code (marked with blue ring)


enter image description here

  • Possible duplicate of [How to break out of multiple loops in Python?](https://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python) – Thierry Lathuille Jun 24 '19 at 12:54
  • What do you think `exit` does? I don't think it does what you want: https://docs.python.org/3/library/constants.html#exit, it doesn't have much effect unless you call it. – mkrieger1 Jun 24 '19 at 12:55
  • And what do you mean by "exit the last exit code"? Which code? – mkrieger1 Jun 24 '19 at 12:58
  • to be clear when you break the first exit line gets run? from my persective i don''t understand the point of putting in a while loop as opposed to saying something like if condition: {try:break} also why is breaking from a loop going to give you a valueError? can you be more specific as to what the point of this code is and what you are trying to accomplish. exiting the last exist code sounds pretty vague. – Sagick Jun 24 '19 at 13:00
  • My point was to make use of a custom exception. Killjoy's answer was what I searched for. Sorry for the unclear question. – vectorizinglife Jun 24 '19 at 13:06

2 Answers2

2

Use a custom exception to break out.

class ExitLoop(Exception):
    pass

try:
    while True:
        while other:
            raise ExitLoop()
except ExitLoop:
    exit()
killjoy
  • 3,665
  • 1
  • 19
  • 16
1

Instead of breaking in the inner loop, set a flag. At the outer loop break if flag is set.

flag = False
while True:
    if flag:
        break
    while otherCondition:
        try:
            flag = True
        except ValueError:
            print('oops')
chris
  • 4,840
  • 5
  • 35
  • 66