← Back to list

Controlling nested loops in Python like in Bash and PHP

Mimicking the power of the break and continue statements from other languages to control the flow of execution.

UnicornOnAzur in Top Python Libraries · 2025-09-05 01:47 · 0 claps · 5.8 min read
#python-programming #python-standard-library #nested-loop #python-control-flow #control-flow-in-python
Open on Medium ↗
Wiki topics: 💻 · Programming 📚 · Books & Reading

Controlling nested loops in Python like in Bash and PHP

Mimicking the power of the break and continuestatements from other languages to control the flow of execution.

While I was watching the live streams of Dave (https://www.youtube.com/@yousuckatprogramming) of the Advent of Code puzzles, he used the break 2 statement in Bash, which lets you exit a nested loop. This is something that is not available in Python. However, you can still get a similar result by utilizing some of Python’s features. Even though using nested loops, particularly three or more, usually signals that it’s time to refactor your code, there are times — like for quick prototyping or tackling an Advent of Code challenge — when this approach might actually be what you need.

Yes, there are already dozens of blogs on using break and continuestatements. However, almost all of them look at one loop or a single nested loop, and few go into more nesting or the working. First, I’ll explain how to use break in nested loops. Then, I’ll cover continue in the same way. Next, I’ll get into the details of how it functions before trying to combine multiple levels of break and continuestatements in a single script.

Image created with magicstudio.com

Image created with magicstudio.com

In Bash, the break and continue statements allow an [n]argument that specifies the loop level to break out of.¹’²’³ In code that could look like this:

for i in {1..3}; do
  for j in {1..3}; do
    if [[ $j -eq 2 ]]; then
      break 2
    fi
    echo "j: $j"
  done
  echo "i: $i"
done

echo 'All Done!'

An example of the use of continue, based of this blog⁴, could be:

[embed]

PHP has similar features for the break⁵ and continue⁶ statements. If you know of any other languages that have this, feel free to share it in the comments.

Exit or ‘break’ the loop

The [break](https://docs.python.org/3/reference/simple_stmts.html#break) statement breaks out of the innermost enclosing [for](https://docs.python.org/3/reference/compound_stmts.html#for) or [while](https://docs.python.org/3/reference/compound_stmts.html#while) loop.⁷

Breaking out of the (inner ) loop

[embed]

In one loop, the break statement breaks the loop and thus ends the iteration. The example will output this.

1
2

Breaking out of the second loop

for i in {1..5}; do
  for j in {1..5}; do
    if [ $j -gt 2 ]; then
       break 2 
    fi
    echo "$i $j"
  done 
done

As mentioned, to break out of two loops, Bash and PHP can use the argument on the break statement. This code example will output this.

1 1
1 2

To achieve the same output in Python, an else block is added to the inner loop containing a continue statement. How this works, I’ll explain later.

[embed]

Breaking out of the third loop

[embed]

To break out of three loops, we repeat the pattern. This will also work for an increasing number of loops by just adding the pattern at the end.

1 a !
1 a @
1 a #
1 a $
1 a %
1 b !
1 b @
1 b #
1 b $
1 b %
1 c !

Continue with the next iteration

The [continue](https://docs.python.org/3/reference/simple_stmts.html#continue) statement continues with the next iteration of the loop.⁷

Continue iteration of one loop

[embed]

In one loop, the continue will signal the next iteration to start. The code above will result in this output.

1
2
4
5

Continue iteration of two loops

[embed]

This example from before will provide the output below. To show the effect of the different arguments provided to the continue statements, two actions are done: one to continue only the inner loop, and one to continue both loops.

1 a 1 b 2 a 3 a 3 b 4 a 4 b 5 a 5 b

The following combination of break and continue statements, will result in the same output.

[embed]

Continue iteration of three or more loops

The following code will mimic the use of continue 3 in Bash.

[embed]

As with using the break on multiple loops, this pattern can be repeated for more loops.

Explanation

Alright, but how does this all work. The break statement at the low level makes a jump forward to the next instruction outside of the current loop.

… the continue statement behaves at a low level exactly like reaching the end of a loop iteration.⁸

These to things result in the way the statements work. To influence loops outside of the inner loop, we can use the else clause because

… the else clause is not executed if the loop was terminated by a [break](https://docs.python.org/3/reference/simple_stmts.html#break).⁹

Looking back at the example breaking out of two loops, the code below will result in the same output.

for i in (1, 2, 3, 4, 5):
    for j in (1, 2, 3, 4, 5):
        if j > 2:
            break
        print(i, j)
    break

The value of the else clause only becomes apparent when then the condition for the first break is never met. When the condition is set to a value larger than the variable ever will become, than this code will print all the values of both ranges.

for i in (1, 2, 3, 4, 5):
    for j in (1, 2, 3, 4, 5):
        if j > 5:
            break
        print(i, j)
    else:
        continue
    break

However, without the else clause the code will break after the first iteration of the outer loop. This approach is also described by others such as GeeksforGeeks¹⁰, StackOverflow¹¹.

for i in (1, 2, 3, 4, 5):
    for j in (1, 2, 3, 4, 5):
        if j > 5:
            break
        print(i, j)
    break

Similarly, for the example of continue the outer of three loops, removing the else clause, i.e., making it like this will result the middle loop breaking after one iteration and the if check never even be met.

for i in range(1, 3):
    for j in ['a', 'b', 'c']:
        for k in range(11, 14):
            if (i, j, k) == (1, 'b', 11):
                print("continue outer loop")
                break
            print(f"{i} {j} {k}")
        break
    continue

Trying to control multiple levels

Given how control flow in Python works, recreating the outcome of a Bash script such as this that breaks and continues loops on multiple levels is not possible using just break, continue, and else.

for i in {1..7}; do
    echo "new outer loop"
    for j in {a..c}; do
        for k in {11..13}; do
            case "$i,$j,$k" in
                "1,b,11")
                    echo "continue inner loop"
                    continue 1
                    ;;
                "2,b,11")
                    echo "continue middle loop"
                    continue 2
                    ;;
                "3,b,11")
                    echo "continue outer loop"
                    continue 3
                    ;;
                "4,b,11")
                    echo "break inner loop"
                    break 1
                    ;;
                "5,b,11")
                    echo "break middle loop"
                    break 2
                    ;;
                "6,b,11")
                    echo "break outer loop"
                    break 3
                    ;;
            esac
            echo "$i $j $k"        
        done
    done
    echo
done

The desired outcome would be this with the additional prints of newline and text emphasizing the point in each loop.

new outer loop
1 a 11
1 a 12
1 a 13
continue inner loop
1 b 12
1 b 13
1 c 11
1 c 12
1 c 13

new outer loop
2 a 11
2 a 12
2 a 13
continue middle loop
2 c 11
2 c 12
2 c 13

new outer loop
3 a 11
3 a 12
3 a 13
continue outer loop
new outer loop
4 a 11
4 a 12
4 a 13
break inner loop
4 c 11
4 c 12
4 c 13

new outer loop
5 a 11
5 a 12
5 a 13
break middle loop

new outer loop
6 a 11
6 a 12
6 a 13
break outer loop

So far, I have not come up with a working example. If I do, it will be here:

[embed]*MWE of breaking and continue nested loops. *MWE of breaking and continue nested loops. GitHub Gist: instantly share code, notes, and snippets. gist.github.com

If you have any thoughts or ideas on how far we’ll be able to get with Python, share those in the comments.

To conclude

Having written this story and figuring out the ways to control the flow, helped me especially gain insight into how the else clause works. And, I now have some nice boilerplate code for the next project, prototype, or Advent of code puzzle.

Diving into the bytecode was interesting. Eventually, I would like to how the break statement works as well.

This story is my way to share my coding experience and the lessons I learned, and to document my solutions. All claps, comments, and highlights are appreciated, as well as sharing the story. For more code and my other links see: https://github.com/UnicornOnAzur/.

[1] https://linuxize.com/post/bash-break-continue/

[2] https://thelinuxcode.com/bash-nested-for-loop/

[3] https://linuxconfig.org/nested-loops-in-bash-scripts

https://shscripts.com/loops-in-linux-shell-scripts/

[4] https://blog.cobrasoft.org/how-to-use-the-continue-command-in-bash/

[5] https://www.php.net/manual/en/control-structures.break.php

[6] https://www.php.net/manual/en/control-structures.continue.php

[7] https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements

[8] https://realpython.com/python-continue/#understanding-the-official-documentation

[9] https://docs.python.org/3/tutorial/controlflow.html#else-clauses-on-loops

[10] https://www.geeksforgeeks.org/python/how-to-break-out-of-multiple-loops-in-python/

[11] https://stackoverflow.com/questions/6346492/how-to-stop-one-or-multiple-for-loops


메타데이터
post_id
219a0adeccb9
slug
controlling-nested-loops-in-python-like-in-bash-and-php-219a0adeccb9
url
https://medium.com/top-python-libraries/controlling-nested-loops-in-python-like-in-bash-and-php-219a0adeccb9
canonical_url
https://medium.com/top-python-libraries/controlling-nested-loops-in-python-like-in-bash-and-php-219a0adeccb9
author_url
https://medium.com/@unicornonazur
status
ok
fetched_at
2026-08-03 23:05:12