Guest User

break out nested loops

a guest
Mar 13th, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.74 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import contextlib
  3.  
  4. @contextlib.contextmanager
  5. def Label(name):
  6.     class _Label(Exception):
  7.         pass
  8.     try:
  9.         yield _Label
  10.     except _Label:
  11.         print("loop break:", name)
  12.  
  13. with Label("label1") as label1:
  14.     for x in range(5):
  15.         print("L1", x)
  16.         with Label("label2") as label2:
  17.             for y in range(10, 50, 10):
  18.                 print("L2", y)
  19.                 for z in range(100, 500, 100):
  20.                     print("L3", z)
  21.                     if x > 1:
  22.                         raise label1()
  23.                     if y > 10:
  24.                         raise label2()
  25.                     if z > 200:
  26.                         print("loop break: L3")
  27.                         break
Advertisement
Add Comment
Please, Sign In to add comment