Setting the Stage: Control Over Loops with Break and Continue

Hello, and welcome to this stimulating session! Today, you will delve into Python loops' governing principles with break and continue. These potent tools can halt a loop mid-way or bypass an iteration.

Sounds thrilling? Let's dive in!

Break: The Loop Controller in For Loops

The break keyword ends a loop before it exhausts all iterations:

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

for planet in planets:
    print(planet)
    if planet == 'Earth':
        print("Found Earth!")
        break

The code prints:

Mercury
Venus
Earth
Found Earth!

In this for loop, once we reach Earth, break terminates the loop. We avoid unnecessary iterations over the remaining planets.

Break: The Loop Controller in While Loops

The break command works similarly in a while loop:

countdown = 10

while countdown > 0:
    print(countdown)
    countdown -= 1
    if countdown == 5:
        print("Time to stop!")
        break

The code prints:

10
9
8
7
6
Time to stop!
Continue: The Loop Skipper

The continue keyword omits a part of the current loop iteration and proceeds to the next:

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

for planet in planets:
    if planet == 'Mars':
        continue
    print(planet)

The code prints:

Mercury
Venus
Earth
Jupiter
Saturn
Uranus
Neptune

After encountering Mars, continue skips the printing command and jumps to the next planet.

Nested Loops and Loop Control

break and continue also operate within nested loops. In them, break only stops the innermost loop it operates in:

celestial_objects_data = [
    ["star", ["observed", "unobserved", "observed"]],
    ["planet", ["unobserved", "unobserved", "observed"]],
    ["galaxy", ["observed", "observed", "observed"]],
    ["comet", ["unobserved", "unobserved", "unobserved", "unexpected"]]
]

for item in celestial_objects_data:
    obj, observations = item
    print('Object:', obj)
    for observation in observations:
        if observation == "unobserved":
            print("An object was missed!")
            break
        if observation != "observed" and observation != "unobserved":
            # Skipping unexpected input
            continue
        print('Status:', observation)

The code prints:

Object: star
Status: observed
An object was missed!
Object: planet
An object was missed!
Object: galaxy
Status: observed
Status: observed
Status: observed
Object: comet
An object was missed!

In this nested loop, break ends the inner loop when encountering an 'unobserved' status. Still, the outer loop continues. Though break and continue provide dynamic flow control in loops, they may complicate debugging when used excessively in nested loops.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal