Python break, continue and pass

In programming, the break and continue statements are used to alter the flow of loops:

  • break exits the loop entirely

  • continue skips the current iteration and proceeds to the next one

Python break Statement

The break statement terminates the loop immediately when it's encountered.

Syntax

Working of Python break Statement

Working of break Statement in Python

The above image shows the working of break statements in for and while loops.

Note: The break statement is usually used inside decision-making statements such as if...else.

Example:

We can use the break statement with the for loop to terminate the loop when a certain condition is met.

In the above example,

terminates the loop when i is equal to 3. Hence, the output doesn't include values after 2.

Note: We can also terminate the while loop using a break statement.

Python continue Statement

The continue statement skips the current iteration of the loop and the control flow of the program goes to the next iteration.

Syntax

Working of continue Statement in Python

Example:

We can use the continue statement with the for loop to skip the current iteration of the loop and jump to the next iteration.

In the above example,

skips the current iteration when i is equal to 3, and continues the next iteration. Hence, the output has all the values except 3.

Note: We can also use the continue statement with a while loop.

continue Statement with while Loop

We can skip the current iteration of the while loop using the continue statement.

In the above example, we have used the while loop to print the odd numbers between 1 and 10. Here,

skips the current iteration when the number is even and starts the next iteration.

Python pass Statement

In Python programming, the pass statement is a null statement which can be used as a placeholder for future code.

Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. In such cases, we can use the pass statement.

The syntax of the pass statement is:

Using pass with conditional Statement

Here, notice that we have used the pass statement inside the if statement .

However, nothing happens when the pass is executed. It results in no operation (NOP).

Suppose we didn't use pass or just put a comment as:

Here, we will get an error message: IndentationError: expected an indented block

Note: The difference between a comment and a pass statement in Python is that while the interpreter ignores a comment entirely, pass is not ignored.

Use of pass Statement inside Function or Class

We can do the same thing in an empty function or class as well.

For example,