Python – Break , Continue And Pass

In Python, break , continue and Pass statements can alter the flow of a normal loop.

Loops iterate over a block of code until the test expression is false, but there are occasions when we want to skip the current iteration or even the entire loop.

The break and continue statements are used in these cases.

 Python supports the following control statements.

  • Break statement
  • Continue statement
  • Pass statement

Python Break Statement

The Python break statement terminates the loop in which it is placed. When a break statement is executed, the statements following the loop’s contents are executed.

Within a nested loop, a break statement can be used. Only the inner loop will stop executing if a break statement appears in a nested loop. The outer loop will execute until all iterations have completed, or until the outer loop is broken with a break statement.

Break statements can be used to exit a loop when a specific condition is met. Within your loop, you declare a break statement, usually under an if statement.

Example: Python break

# Use of break statement inside the loop

for val in "codelivly":
    if val == "i":
        break
    print(val)

print("The end")

Output

c
o
d
The end

Python Continue statement

Like the break statement, continue is a loop control statement. The continue statement is the polar opposite of the break statement in that it forces the loop to perform the next iteration rather than ending it.
The continue statement, as the name implies, forces the loop to continue or execute the next iteration. When the continue statement is used in a loop, the code inside the loop that follows the continue statement is skipped, and the loop’s next iteration begins.

Example: Python continue

students = ["Rocky", "Bikash"]

for student in range(0, len(students)):
	if student == 2:
		continue
    else:
		print(students[student])

	print("Code is " + str(student))

print("Program Complete")

Our code returns the following:

Rocky
Code is 0
Bikash
Code is 1

Python Pass statement

The pass statement is a null statement in Python programming. The difference between a comment and a pass statement in Python is that a remark is completely disregarded by the interpreter, whereas pass is not.

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

Example: pass Statement

'''pass is just a placeholder for
functionality to be added later.'''
sequence = {'p', 'a', 's', 's'}
for val in sequence:
    pass

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

def function(args):
    pass
class Example:
    pass

Leave a Comment

Your email address will not be published.