Loops in Python are used to execute a block of code iteratively for a number of times or until the list is exhaustive. But sometimes, in this form of execution, we require some exceptions like skipping an iteration, coming out of the loop when a specific condition is met, or disregard a condition. This can be achieved using Loop Control Statements in Python. These statements help us to alter the flow of a normal loop.
The types of Loop Control statements available in Python are:
Suppose we wish to come out of the loop when a specific condition is met and not iterate further for the remaining iterations, we use the break statement. Therefore, the break statement helps us to exit the control of the loop before its predefined time. We exit the loop when the exiting condition is met.
Here, you can see that we exit the loop when our if condition is met since it is followed by a break statement.
The continue statement helps us to skip a particular iteration. Therefore, when we wish to skip a particular iteration and run the loop for the remaining iterations then we would go for the continue statement. It rejects all the statements in the current iteration and returns the control of the loop at the beginning of the loop instead of terminating the loop.
Here, we can see that the iteration when n is equal to 2 is skipped, and rest all the iterations are performed.
The pass statement acts as a null statement which helps us to handle a specific condition without impacting the loop in any way. Therefore, if we wish to disregard a particular condition or not let a specific condition affect the loop then we use the pass statement. Hence, nothing happens when pass is executed.
Here, we can see that the same condition is disregarded and 2 is printed in the output.
Therefore, these loop control statements – break, continue, and pass help us to fine-tune loop control according to our requirements.