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:
The code prints:
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:
The code prints:
The continue keyword omits a part of the current loop iteration and proceeds to the next:
The code prints:
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:
The code prints:
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.
