Loop Control Statements in Python (With Examples)

loop-control-statements-break-continue-pass-in-python

In the previous tutorial, we learn about the while loop and for loop in python. In this tutorial, we are going to discuss loop control statements in python.

Loop control statements are essential programming constructs that allow developers to control the flow of iterations in loops.

In Python, there are three primary loop control statements:

  • “break”
  • “continue”
  • “pass”

“break” Statement in Python:

break statement in python is used to terminate a loop prematurely.

When the Python interpreter encounters a break statement, it immediately exits the loop, regardless of how many iterations are left.

This statement is useful when you want to stop a loop once a certain condition is met.

For example, the following code breaks out of a loop when the value of the counter variable is equal to 5:

Code:

for i in range(1, 11):
    if i == 5:
        break
    print(i)

Output:

This code will output the following values:

1
2
3
4

“continue” Statement in Python:

continue is used to skip the current iteration of a loop and move on to the next one.

This statement is useful when you want to skip over certain values in a loop without terminating it altogether.

For example, the following code skips the iteration when the value of the counter variable is equal to 5:

Code:

for i in range(1, 11):
    if i == 5:
        continue
    print(i)

Output:

This code will output the following values:

1
2
3
4
6
7
8
9
10

“pass” Statement in Python:

pass is a placeholder statement that does nothing.

It is used when you need to include a statement in your code for syntactical reasons, but you do not want it to do anything.

For example, the following code includes a pass statement inside a loop:

Code:

for i in range(1, 11):
    pass

This code will not produce any output.

So, loop control statements are an essential tool for controlling the flow of iterations in loops.

By using break, continue, and pass, developers can write more efficient and effective code that meets their specific needs.

So, in the next tutorial, we are going to learn about Truthness and Falseness in Python. So, make sure to subscribe to us to learn python in an easy way.


Discover more from Python Mania

Subscribe to get the latest posts sent to your email.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Related Articles:

Recent Articles:

0
Would love your thoughts, please comment.x
()
x

Discover more from Python Mania

Subscribe now to keep reading and get access to the full archive.

Continue reading