Break, Pass and Continue Statement in Python

Video Tutorial
FREE
Control flow: break and continue thumbnail
This video belongs to
Python and SQL for Data Science
8 modules
Certificate

Overview

break, pass, and continue statements are provided in Python to handle instances where you need to escape a loop fully when an external condition is triggered or when you want to bypass a section of the loop and begin the next iteration. These statements can also help you gain better control of your loop.

Break Statement in Python

Python provides us with a particular purpose statement – break. It is worth noting that the break statement can only be used within the for and while loops. Once the program encounters the break statement, it terminates the loop immediately, and the lines of code written right after the body of the loop continue to execute.

The break statement in Python will cause the loop to end even if the while loop condition evaluates to True, or in the case of for loop. It will cause the control of the program to jump out of the for loop even if it satisfies the condition.

A typical example of when the break statement is used is during a sequential search. For example, you’re searching for an element in a list of elements using a for a loop. You will add in a comparison condition, to check if the element is found. If the element is found, then you would exit from the loop without traversing the remaining elements.

Here is a flowchart of how the break statement works in Python to give you better clarity.

Break Statement in Python

Syntax of Break Statement in Python

The syntax is pretty simple, you just have to put in the keyword break when you want the loop to terminate. Let’s look at some pseudo-code.

Syntax of Break Statement in Python The above pseudo-code is for the for loop.

Break Statement in Python - While loop The above pseudo-code is for the while loop.

Implementation of Break Statement in Python

Now that we know what the break keyword is, what it does and how to use it, let us look at some more examples.

Let’s say we want to write a program that is set to print the first seven items in a list, but if it encounters the number ‘4’, we need to exit the loop. We can easily do this using the break statement in Python.

Example:

Output:

Explanation:

Now in this program, we added a condition wherein if we encounter the number 4, we need to break the loop. And since we encountered a 4, the loop breaks immediately.

What if there was no 4?

Example:

Output:

Since the program did not encounter any 4, the control does not jump out of the loop, and the loop continues to run.

What if the break statement is used in a nested loop? In that case, the break statement will cause the program to jump out of the loop that the break statement is part of and move the control to the first line after the body of the loop containing break. If it was used in the outermost loop itself, it would exit the loops and move directly to any statements written outside the loops and continue executing the program.

Example:

Output:

That’s all for the break statement!

Pass Statement in Python

Let’s now talk about doing nothing in Python. Seems odd? But yes, the pass statement does nothing. For doing nothing, it’s a pretty useful statement. The syntax of the pass statement is the same as a break.

Why do we Use Pass Statement in Python?

To do nothing inside a block of code, you can use the pass statement.

Example:

Output:

But this doesn’t seem useful, does it? Not writing the pass statement there wouldn’t make any difference in the code, and it would also make the code shorter. Why does the python syntax have a statement that tells the interpreter to do nothing?

The statement can be used to fulfill a place in a block of code that needs at least 1 statement.

Example:

You have this piece of code, and you really do not know at this point of time, what the values of a and b will be, and what you will be doing if the condition evaluates to True. You want to leave the body empty, but you cannot do that because just running this piece of code would give you an indentation error. Why? Because after the colon (:), Python expects an indented block of code, even if it is a single line or a single statement.

Here, we can make use of the pass statement in Python.

Thanks to the pass statement, we won’t be receiving any errors.

There are more uses of the pass statement, some temporary and some permanent.

Temporary Uses of Pass Statement in Python

The pass statement can be used to fill in code initially that could be used in the future. It may sound silly to use the pass statement in parts of the code that would be deleted anyway later, but it proves to be very useful in the initial stages of development for faster development.

Example:

Say you have a function to do a task that calls another function. But the problem here is that you don’t know how the function you’re calling works. So, you use the pass statement in Python.

This function, func2, doesn’t do anything right now, but it lets you run and test fun1 without any errors.

Another use case for the pass statement is when you just want to understand the structure of the code before going into its complexities.

Example:

In a FizzBuzz code ( a game in which you start from 1, count to 100, and say "Fizz", if the number is divisible by 3, "Buzz" if it is divisible by 5, and "FizzBuzz" if the number is divisible by both 3 and 5 ):

This helps you understand the structure of the code before you go into the if -elif statements to complete the code.

These are a few temporary uses of the pass statement in Python. It also has permanent use cases like :

1. Exception Catching:

In python, we use the tryexcept block for handling errors. Sometimes, you might not want to do anything upon encountering an error. In that case, you can use the pass statement. Let me show you an example.

This function above removes the file mentioned and does not fail if the file does not exist. If the file you want to remove does not exist, you need not do anything. So when the FileNotFoundError is raised, you can simply use the pass statement.

2. If…Elif Chains

Say in an interview, you’re asked a basic FizzBuzz question, except with a little twist. If the input number is divisible by 3, print Fizz. If divisible by 5, print Buzz. If divisible by 15, print nothing, and if divisible by 20, print Twist.

Clearly we can see that the use of the pass statement in Python allows you to avoid refactoring the logic. You are also able to structure the code according to its description.

Continue Statement in Python

Continue is also one of the useful loop control statements in Python. It is almost the opposite of the break statement discussed above. Break terminates the loop, and the continue statement forces the program to execute the next iteration of the loop.

Also Read- Difference Between Break and Continue Statements in Python.

When the program control encounters the continue statement, the code following the continue statement (if any) will be skipped, and the next iteration of the loop will begin.

Continue Statement in Python example

We can understand the use of the continue statement in Python with an example.

As we can see in the code above, the code after the continue statement does not get executed, hence omitting the print statement when the letter 'o' is encountered. We directly move to the next iteration of the loop.

Of course, the above code could have been written in various other ways without using the continue statement. Let us understand its importance in readability and how it reduces expensive run time with an example.

You have two lists, x, and y. You’d like to zip (a function that generates an iterator of a series of tuples) them and perform some functions on them depending upon two values of a and b, which belong to the result of zip.

Here’s some code without the continue statement. Notice how it looks all over the place with nested if statements, decreasing the readability.

Now here, the nested if statements might make the code look confusing. Watch how the continue statement helps make this code better :

Notice how this is more readable and convenient to write?

Conclusion

  1. Break, Pass, and Continue statements are loop controls used in python.
  2. The break statement, as the name suggests, breaks the loop and moves the program control to the block of code after the loop (if any).
  3. The pass statement is used to do nothing.
    • Two of its uses are :
      • Exception Catching
      • If elif chains
  4. The continue statement in Python is the opposite of the break statement and is used to force the next iteration of the loop. Any lines of code after the continue statement in the loop will not be executed.

See Also: