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 pass, break, 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 if, for, 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 suite1. 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():
passBut why would we want a compound statement to do nothing in the first place?
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.
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.
Related Articles
Thanks for reading! You can sign up for my newsletter to receive updates on my new articles. If you’re interested in Python, you might be interested in the following articles:
Happy Coding!
No comments:
Post a Comment