6.6 Loop control statements
Loop control statements in Python - break
, continue
, and pass
allow us to control the flow of loops (for-in
and while
loops).
6.6a break
statement
The break
statement terminates the loop entirely. When break is encountered inside a loop, the loop stops immediately, and the program continues with the next statement following the loop.
Example 6.6.1 - In this example, the loop will print numbers from 0 to 4. When i
is 5, the break
statement is executed, and the loop terminates.
Example 6.6.1 - Output
0 1 2 3 4
6.6b continue
statement
The continue
statement skips the rest of the code inside the loop for the current iteration and moves to the next iteration of the loop.
Example 6.6.2 - In this example, the loop will print only the odd numbers from 0
to 9
. When i
is an even number, the continue
statement is executed, and the rest of the code inside the loop is skipped for that iteration.
Example 6.6.2 - Output
1 3 5 7 9
6.6c pass
statement
The pass
statement is a null operation; nothing happens when it is executed. It’s used as a placeholder for future code. This can be useful in places where your code requires a statement syntactically, but you haven’t decided what to do there yet.
Example 6.6.3 - In this example, the pass statement is used as a placeholder within the if block. It doesn’t affect the loop’s execution.
Example 6.6.3 - Output
1 3 5 7 9
6.6d Summary of loop control statements
break
- Exits the loop immediately.continue
- Skips the rest of the code inside the loop for the current iteration and proceeds to the next iteration.pass
- Does nothing; it's a placeholder that allows you to write syntactically correct empty code.