/ 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. = 10
  2. n = 240
  3. for x in range(r):
  4. for y in range(r):
  5. for z in range(r):
  6. # Start reading here
  7. if x * y * z == n:
  8. print(x,y,z)
  9. # 5 6 8
  10. break
  11. else:
  12. continue
  13. break
  14. else:
  15. continue
  16. break
  1. const int r(10 );
  2. const int n(240);
  3. for ( int x = 0; x < r; x++ ) {
  4. for ( int y = 0; y < r; y++ ) {
  5. for ( int z = 0; z < r; z++ ) {
  6. // Start reading here
  7. if ( x * y * z == n ) {
  8. qDebug() << x << y << z;
  9. goto finished;
  10. }
  11. }}} finished:

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