How to Use Pass, Break, and Continue in Python 3 ways to exit a clause in Python

Learning how to code in Python isn’t easy. Maybe you’ve leveraged compound statements in Python that contain groups of other statements, or clauses that affect the flow of control. Have you ever encountered scenarios where you were unable to implement what you want in loops or if-else?

You might need to know more about how to exit a clause using passbreak, and continue. Before learning these three methods, get familiar with some built-in Python features in this article:

Clause

A clause in Python — such as iffor, and while loop — consists of a header and its suite separated by a colon :. The number of times its suite is executed depends on the satisfaction of the header condition.

# The following is a clause
if a > 0: # This is a header
print(a) # This is a suite

1. Pass

Let’s start with something relatively easy (but not straightforward). Nothing happens when pass is executed. Its main purpose is to act as a placeholder where the interpreter expects a statement.

Remember a colon-separated compound statements needs a header and a suite? If you want a suite to do nothing, you cannot end the statement with the colon :. This is where pass comes in handy, as a statement is syntactically required.

def foo():
pass

But why would we want a compound statement to do nothing in the first place?

Image for post
Photo by Federico Bottos on Unsplash

If there’s a function or a loop that we would like to implement in the future, we might construct an empty function or loop first with an empty body. Since this is syntactically illegal, we use the null statement pass as a placeholder to comply with the syntax requirement.

This is useful for creating an empty clause in project development.


2. Break

The break statement allows you to leave a for or while loop prematurely.

In the following example, the break statement is executed when a == 2 is satisfied. It terminates the loop early. The for-loop control target (i.e. a in this case) keeps its current value when break is executed.

You can also exit a while loop early using break in a similar fashion. No loops can resist break, not even a while True loop that could execute its suite indefinitely.

Image for post
Photo by Kalen Emsley on Unsplash

3. Continue

The continue statement ignores the rest of the statements inside a loop, and continues with the next iteration. Note that continue does not halt the loop like break does, but rather skips and carries on to the next iteration.


Comments

Popular posts from this blog

Flutter for Single-Page Scrollable Websites with Navigator 2.0

A Data Science Portfolio is More Valuable than a Resume

Better File Storage in Oracle Cloud