/ home / Programming / Python /

Breaking Out of Nested Loops

From inside a loop, nested within another loop [etc], returning to the base code block.

Python Qt/Cpp
  1. # Special thanks from jinsuun__ on #python irc
  2. from dataclasses import dataclass
  3. @dataclass
  4. class C:
  5. m_c: int
  6. isLetter : bool = False
  7. isNonCharacter : bool = False
  8. isNull : bool = False
  9. isNumber : bool = False
  10. isPrintable : bool = True
  11. isSpace : bool = False
  12. isUpper : bool = False
  13. n = 88
  14. c = C(n)
  15. match c:
  16. case C(0):
  17. c.isNull = True
  18. case C( m_c = x ) if x in range( 1, 32 ) or x == 127:
  19. c.isNonCharacter = True
  20. c.isPrintable = False
  21. case C(" "):
  22. c.isSpace = True
  23. case C(x) if x in range( ord("A"), ord("Z") + 1 ):
  24. c.isUpper = True
  25. c.isLetter = True
  26. case C(x) if x in range( ord("a"), ord("z") + 1 ):
  27. c.isUpper = False
  28. c.isLetter = True
  29. case C(x) if x in range( ord("0"), ord("9") + 1 ):
  30. c.isNumber = True
  31. case _:
  32. pass
  1. qint8 c(88);
  2. bool isLetter (false);
  3. bool isNonCharacter(false);
  4. bool isNull (false);
  5. bool isNumber (false);
  6. bool isPrintable (true );
  7. bool isSpace (false);
  8. bool isUpper (false);
  9. switch (c) {
  10. default: break;
  11. case 0 :
  12. isNull = true;
  13. [[fallthrough]];
  14. case 1 ... 31:
  15. case 127 : // Delete
  16. isNonCharacter = true;
  17. isPrintable = false;
  18. break;
  19. case ' ':
  20. isSpace = true;
  21. break;
  22. case 'A' ... 'Z':
  23. isUpper = true;
  24. [[fallthrough]];
  25. case 'a' ... 'z':
  26. isLetter = true;
  27. break;
  28. case '0' ... '9':
  29. isNumber = true;
  30. break;
  31. }

Read as:
  • if [ expression is true ]
  • print x y z
  • 'break'out of loop z [ ignore the else ]
  • 'break'out of loop y [ ignore the else ]
  • 'break'out of loop x.
  • if [ expression is true ]
  • debug out x y z
  • and goto finished [ label ]

Benefits:
  • In python, you can place an "else" statement after a loop ( "for" or "while" ) which gets called if the loop exits without a 'break' statement. This is a novell construct absent in c++."
  • This code, is clean, and in this particular case, no extra indentation was needed.
  • the "goto" label is particularly descriptive: "[ I am finished ] goto finish line."

Drawbacks:
  • This "else" feature is esoteric and unknown towards most Python developers.
  • The "else" mistakenly seems like the continuation to the "if" statement above.
  • This feature does not exist in any other language, making this a non-transferable idiom.
  • Indentation structure is bumpy and disorienting.
  • None.

Final Thoughts