Loop Control Statements in Python

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:

  1. break
  2. continue
  3. pass

Break Statement

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.

Syntax:
break
Example:
Output:

Here, you can see that we exit the loop when our if condition is met since it is followed by a break statement.

Continue 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.

Syntax:
continue
Example:
Output:

Here, we can see that the iteration when n is equal to 2 is skipped, and rest all the iterations are performed.

Pass Statement

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.

Syntax:
pass
Example:
Output:

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.

About the Author

Jinal Shah

Graduate in Applied Statistics & Analytics (NMIMS) and Aspiring Actuary

Comments 1

  1. Great article on loop control statements in Python! Break allows us to exit the loop prematurely, continue skips an iteration, and pass helps handle conditions without impacting the loop. These statements give us precise control over loop execution. Well explained!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.