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!
The break
keyword ends a loop before it exhausts all iterations:
Python1planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] 2 3for planet in planets: 4 print(planet) 5 if planet == 'Earth': 6 print("Found Earth!") 7 break
The code prints:
Markdown1Mercury 2Venus 3Earth 4Found Earth!
In this for
loop, once we reach Earth, break
terminates the loop. We avoid unnecessary iterations over the remaining planets.
The break
command works similarly in a while
loop:
Python1countdown = 10 2 3while countdown > 0: 4 print(countdown) 5 countdown -= 1 6 if countdown == 5: 7 print("Time to stop!") 8 break
The code prints:
Markdown110 29 38 47 56 6Time to stop!
The continue
keyword omits a part of the current loop iteration and proceeds to the next:
Python1planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] 2 3for planet in planets: 4 if planet == 'Mars': 5 continue 6 print(planet)
The code prints:
Markdown1Mercury 2Venus 3Earth 4Jupiter 5Saturn 6Uranus 7Neptune
After encountering Mars, continue
skips the printing command and jumps to the next planet.
break
and continue
also operate within nested loops. In them, break
only stops the innermost loop it operates in:
Python1celestial_objects_data = [ 2 ["star", ["observed", "unobserved", "observed"]], 3 ["planet", ["unobserved", "unobserved", "observed"]], 4 ["galaxy", ["observed", "observed", "observed"]], 5 ["comet", ["unobserved", "unobserved", "unobserved", "unexpected"]] 6] 7 8for item in celestial_objects_data: 9 obj, observations = item 10 print('Object:', obj) 11 for observation in observations: 12 if observation == "unobserved": 13 print("An object was missed!") 14 break 15 if observation != "observed" and observation != "unobserved": 16 # Skipping unexpected input 17 continue 18 print('Status:', observation)
The code prints:
Markdown1Object: star 2Status: observed 3An object was missed! 4Object: planet 5An object was missed! 6Object: galaxy 7Status: observed 8Status: observed 9Status: observed 10Object: comet 11An 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.
Give yourself a pat on the back; you've just overcome a significant hurdle in your Python learning journey! You've deciphered how to control loops using break
and continue
. You have understood their roles in single and nested loops. Upcoming hands-on exercises will further refine these concepts. Brace yourselves, and let's dive in!