The Wayback Machine - https://web.archive.org/web/20241002055838/https://www.geeksforgeeks.org/break-continue-and-pass-in-python/
Open In App

break, continue and pass in Python

Last Updated : 12 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. These can be done by loop control statements. Loop control statements change execution from their normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements:

Break Statement in Python

The break statement in Python is used to terminate the loop or statement in which it is present. After that, the control will pass to the statements that are present after the break statement, if available. If the break statement is present in the nested loop, then it terminates only those loops which contain the break statement. 

Syntax of Break Statement

The break statement in Python has the following syntax:

for / while loop:
# statement(s)
if condition:
break
# statement(s)
# loop end

Working on Python Break Statement

The working of the break statement in Python is depicted in the following flowchart:

Working of Python Break Statement

Working of Python Break Statement

Example:

In this example, we will see the usage of break statements with Python loops and strings. First, we will use the break statement with for loops to exit out of the for loop when specific characters are encountered in the string. Then we will perform the same operation but with the while loop.

Python
# Python program to demonstrate
# break statement

s = 'geeksforgeeks'
# Using for loop
for letter in s:

    print(letter)
    # break the loop as soon it sees 'e'
    # or 's'
    if letter == 'e' or letter == 's':
        break

print("Out of for loop")
print()

i = 0

# Using while loop
while True:
    print(s[i])

    # break the loop as soon it sees 'e'
    # or 's'
    if s[i] == 'e' or s[i] == 's':
        break
    i += 1

print("Out of while loop")

Output:

g
e
Out of for loop
g
e
Out of while loop

Example:

In this example, we will see the usage of break statements with nested for loops in Python. If the break statement is declared within the inner for loop, then the control comes out of only that loop. The outer for loops still continues to work.

Python
# Python program to demonstrate
# break statement with nested
# for loop

# first for loop
for i in range(1, 5):
  
    # second for loop
    for j in range(2, 6):
      
        # break the loop if
        # j is divisible by i
        if j%i == 0:
            break
            
        print(i, " ", j)

Output:

3   2
4 2
4 3

Continue Statement in Python

Continue is also a loop control statement just like the break statement. continue statement is opposite to that of the break statement, instead of terminating the loop, it forces to execute the next iteration of the loop. As the name suggests the continue statement forces the loop to continue or execute the next iteration. When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin.

Syntax of Continue Statement

The continue statement in Python has the following syntax:

for / while loop:
# statement(s)
if condition:
continue
# statement(s)

Working of Python Continue Statement

The working of the continue statement in Python is depicted in the following flowchart:

Working of Python Continue Statement

Working of Python Continue Statement

Example:

In this example, we will use Python continue statement with for loop to iterate through a range of numbers and to continue to the next iteration without performing the operation on that particular element when some condition is met.

Python
# Python program to
# demonstrate continue
# statement

# loop from 1 to 10
for i in range(1, 11):

    # If i is equals to 6,
    # continue to next iteration
    # without printing
    if i == 6:
        continue
    else:
        # otherwise print the value
        # of i
        print(i, end = " ")

Output:

1 2 3 4 5 7 8 9 10 

Pass Statement in Python

As the name suggests pass statement simply does nothing. The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. It is like a null operation, as nothing will happen if it is executed. Pass statements can also be used for writing empty loops. Pass is also used for empty control statements, functions, and classes.

Syntax of Pass Statement

The pass statement in Python has the following syntax:

function/ condition / loop:
pass

Example: 

In this example, we will use the pass statement with an empty for loop and an empty Python function. We just declared a function and write the pass statement in it. When we try to call this function, it will execute and not generate an error.

Then we use the pass statement with an if condition within a for loop. When the value of “i” becomes equal to ‘k’, the pass statement did nothing, and hence the letter ‘k’ is printed.

Python
# Python program to demonstrate
# pass statement

s = "geeks"

# Empty loop
for i in s:
    # No error will be raised
    pass

# Empty function
def fun():
    pass

# No error will be raised
fun()

# Pass statement
for i in s:
    if i == 'k':
        print('Pass executed')
        pass
    print(i)

Output:

g
e
e
Pass executed
k
s

break, continue and pass in Python – FAQs

What is Break, Continue, and Pass in Python?

Break: The break statement in Python is used to exit a loop prematurely, regardless of the condition of the loop. When Python encounters a break statement, it immediately terminates the loop and proceeds with the next line of code outside the loop.

Continue: The continue statement in Python is used to skip the remainder of the code inside a loop for the current iteration only. The loop does not terminate but proceeds to the next iteration.

Pass: The pass statement in Python is a null operation; nothing happens when it is executed. It is used as a placeholder in a block where Python expects an expression.

What is the Difference Between Continue and Break in Python for Loop?

The continue statement skips the rest of the code inside the loop for the current iteration and moves to the next iteration of the loop. The break statement, on the other hand, completely terminates the loop and transfers execution to the code immediately following the loop.

Example:

for i in range(5):
if i == 3:
continue
print(i) # This will print 0, 1, 2, 4

for i in range(5):
if i == 3:
break
print(i) # This will print 0, 1, 2

What is the Difference Between Break and Quit in Python?

The break statement is used to exit a loop, while quit() is a built-in Python function that exits from Python itself, closing down the Python interpreter. quit() is typically used in interactive sessions rather than in production code.

What is __init__ in Python?

__init__ is a special method in Python, commonly known as the constructor. It is automatically called when a new instance of a class is created. The main purpose of __init__ is to initialize the attributes of the class for the new object by assigning values to them. This method may accept arguments to pass data to initialize the object.

Example:

class Car:
def __init__(self, make, model):
self.make = make
self.model = model

car1 = Car("Toyota", "Corolla")
print(car1.make) # Outputs: Toyota
print(car1.model) # Outputs: Corolla

This setup of using break, continue, and pass provides control over loop execution, while __init__ serves as a fundamental part of class definition in Python, crucial for initializing new objects.



Similar Reads

Loops and Control Statements (continue, break and pass) in Python
Python programming language provides the following types of loops to handle looping requirements. Python While Loop Until a specified criterion is true, a block of statements will be continuously executed in a Python while loop. And the line in the program that follows the loop is run when the condition changes to false. Syntax of Python Whilewhile
4 min read
Difference between continue and pass statements in Python
Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. These can be done by loop control statements. Loop control statements change execution from its normal sequence. When execution leaves a scop
3 min read
Python Continue Statement
Python Continue Statement skips the execution of the program block after the continue statement and forces the control to start the next iteration. Python Continue StatementPython Continue statement is a loop control statement that forces to execute the next iteration of the loop while skipping the rest of the code inside the loop for the current i
4 min read
Python EasyGUI – Continue Cancel Box
Continue Cancel Box : It is used to display a window having a two option continue or cancel in EasyGUI, it can be used where there is a need to display two option continue or cancel for example when we want to confirm the option if continue is pressed application will move forward else it will get terminated, below is how the continue cancel box lo
3 min read
PyQt5 QCalendarWidget - Continue functions by enabling
In this article, we will see how we can continue the functions of the QCalendarWidget. Stopping function means that the QCalendarWidget will not be able to do a single thing like selection changing date etc. Disabling the calendar do not delete or hide the widget from the screen. Disabling is used to stop the user from doing any changes on it, but
2 min read
Python | Split and Pass list as separate parameter
With the advent of programming paradigms, there has been need to modify the way one codes. One such paradigm is OOPS. In this, we have a technique called modularity, which stands for making different modules/functions which perform independent tasks in program. In this, we need to pass more than just variable, but a list as well. Let's discuss cert
4 min read
Pass function and arguments from node.js to Python
Prerequisites: How to run python scripts in node.js using the child_process module. In this article, we are going to learn how to pass functions and arguments from node.js to Python using child_process. Although Node.js is one of the most widely used web development frameworks, it lacks machine learning, deep learning, and artificial intelligence l
4 min read
Break a long line into multiple lines in Python
Break a long line into multiple lines, in Python, is very important sometime for enhancing the readability of the code. Writing a really long line in a single line makes code appear less clean and there are chances one may confuse it to be complex. Example: Breaking a long line of Python code into multiple lines Long Line: a = 1 + 2 + 3 + 4 - 5 * 2
4 min read
Python | Group elements on break positions in list
Many times we have problems involving and revolving around Python grouping. Sometimes, we might have a specific problem in which we require to split and group N element list on missing elements. Let's discuss a way in which this task can be performed. Method : Using itemgetter() + map() + lambda() + groupby() This task can be performed using the co
2 min read
Create a Python Script Notifying to take a break
We generally do not take breaks when we are using our laptop or PC. It might affect our eyesight as well as mind. So with Python, we can make a program that can notify us that we have to take a break start again after sometime when the user again starts working on the laptop. Modules neededpyttsx3 - It is a text-to-speech conversion library in Pyth
4 min read
Working with Page Break - Python .docx Module
Prerequisites: docx Word documents contain formatted text wrapped within three object levels. Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Python doc
2 min read
Break a list comprehension Python
Python's list comprehensions offer a concise and readable way to create lists. While list comprehensions are powerful and expressive, there might be scenarios where you want to include a break statement, similar to how it's used in loops. In this article, we will explore five different methods to incorporate the 'break' statement in Python list com
2 min read
Python break statement
Python break is used to terminate the execution of the loop.  Python break statement Syntax:Loop{ Condition: break }Python break statementbreak statement in Python is used to bring the control out of the loop when some external condition is triggered. break statement is put inside the loop body (generally after if condition).  It terminates the cur
4 min read
Break a list into chunks of size N in Python
In this article, we will cover how we split a list into evenly sized chunks in Python. Below are the methods that we will cover: Using yieldUsing for loop in PythonUsing List comprehensionUsing NumpyUsing itertoolMethod 1: Break a list into chunks of size N in Python using yield keywordThe yield keyword enables a function to come back where it left
7 min read
How to write an empty function in Python - pass statement?
In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa
1 min read
Pass list as command line argument in Python
The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. One of them is sys module. sys Module A module is a file containing Python definitions and statements. The sys module provides functi
3 min read
How to pass argument to an Exception in Python?
There might arise a situation where there is a need for additional information from an exception raised by Python. Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the following reasons: It can be used to gain additional
2 min read
Python - pass multiple arguments to map function
The map() function is a built-in function in Python, which applies a given function to each item of iterable (like list, tuple etc.) and returns a list of results or map object. Syntax : map( function, iterable ) Parameters : function: The function which is going to execute for each iterableiterable: A sequence or collection of iterable objects whi
3 min read
Digital Low Pass Butterworth Filter in Python
In this article, we are going to discuss how to design a Digital Low Pass Butterworth Filter using Python. The Butterworth filter is a type of signal processing filter designed to have a frequency response as flat as possible in the pass band. Let us take the below specifications to design the filter and observe the Magnitude, Phase & Impulse R
4 min read
Digital High Pass Butterworth Filter in Python
In this article, we are going to discuss how to design a Digital High Pass Butterworth Filter using Python. The Butterworth filter is a type of signal processing filter designed to have a frequency response as flat as possible in the pass band. Let us take the below specifications to design the filter and observe the Magnitude, Phase & Impulse
5 min read
Digital Band Pass Butterworth Filter in Python
In this article, we are going to discuss how to design a Digital Low Pass Butterworth Filter using Python. The Butterworth filter is a type of signal processing filter designed to have a frequency response as flat as possible in the pass band. Let us take the below specifications to design the filter and observe the Magnitude, Phase & Impulse R
5 min read
Implement Photoshop High Pass Filter (HPF) using OpenCV in Python
In this article, we will discuss how to implement photoshop High Pass Filter (HPF) image in Python OpenCV. High Pass Filter When we talk about Digital Signal Processing or Digital Image Processing Filters are the most fundamental concept. A Filter or a Digital Filter is used to sifting out the unwanted frequency response from the signals. A filter
5 min read
How to pass an array to a function in Python
In this article, we will discuss how an array or list can be passed to a function as a parameter in Python. Pass an array to a function in Python So for instance, if we have thousands of values stored in an array and we want to perform the manipulation of those values in a specific function, that is when we need to pass an entire array to the speci
4 min read
Python pass Statement
The Python pass statement is a null statement. But the difference between pass and comment is that comment is ignored by the interpreter whereas pass is not ignored. The Syntax of the pass statementpassWhat is pass statement in Python? When the user does not know what code to write, So user simply places a pass at that line. Sometimes, the pass is
3 min read
Pass Arguments to the Metaclass from the Class in Python
Metaclasses in Python provide a powerful way to control the creation and behavior of classes. They act as the "class of a class" and allow you to customize class creation and behavior at a higher level. One interesting aspect of metaclasses is the ability to pass arguments from a class to its metaclass during the class definition. What is a Metacla
3 min read
How to pass optional parameters to a function in Python?
In Python, when we define functions with default values for certain parameters, it is said to have its arguments set as an option for the user. Users can either pass their values or can pretend the function to use theirs default values which are specified. In this way, the user can call the function by either passing those optional parameters or ju
5 min read
Pass by reference vs value in Python
Developers jumping into Python programming from other languages like C++ and Java are often confused by the process of passing arguments in Python. The object-centric data model and its treatment of assignment are the causes of the confusion at the fundamental level. In the article, we will be discussing the concept of how to pass a value by refere
7 min read
Pass JavaScript Variables to Python in Flask
In this tutorial, we'll look at using the Flask framework to leverage JavaScript variables in Python. In this section, we'll talk about the many approaches and strategies used to combine the two languages, which is an essential step for many online applications. Everything from the fundamentals to more complex subjects, such as how to handle enormo
7 min read
How to Fix - "Runtimeerror: Package Fails to Pass a Sanity Check" For Numpy and Pandas
Encountering errors during package installations can be a frustrating experience for Python developers. One such error, "RuntimeError: Package Fails To Pass A Sanity Check," often arises due to compatibility issues or conflicts between Python versions and package versions. In this article, we'll address how to resolve this error specifically when u
2 min read
How To Break Up A Comma Separated String In Pandas Column
Pandas library is a Python library which is used to perform data manipulation and analysis. It offers various 2D data structures and methods to work with tables. Some times, the entire data can be in the format of string, which needed to be broken down in-order to organize the information in the pandas data structures. In this article, let us under
4 min read
Article Tags :
Practice Tags :