Python Pass Statement: Ultimate Guide With Examples

by | Python

As the great Pablo Picasso once said, “Every act of creation is first an act of destruction.” In the world of Python programming, this quote rings true with the power of the “pass” statement — a seemingly innocuous keyword with profound implications for how you shape and structure your code.

The Python pass statement serves as a placeholder in Python code, allowing developers to maintain the structure of their program without executing any actions. Commonly used as a temporary measure, the pass statement can be found in loops, conditionals, functions, and class definitions when a block of code requires further development or debugging.

In this article, we’ll explore various examples of how and when to use the pass statement effectively. By mastering this concept, you’ll be able to write better-structured code with ease, making your development process smoother and more productive.

Python Pass Statement with examples

What is the Python Pass Statement?

The pass statement in Python is a unique keyword that serves as a placeholder in situations where a statement is needed syntactically, but you don’t want any action to be performed. Essentially, when the pass statement is executed, it results in a null operation (NOP).

This means no operation is performed, and the interpreter continues to execute any subsequent code. Let’s take a look at its syntax:


In this context, the keyword can be a conditional, a loop, a function, etc. By using pass, you can define empty functions, classes, and conditional statements that don’t produce any errors but can be filled in later as your project progresses.

Here is an example that demonstrates the use of pass in an if statement:

n = 10
if n > 10:
    print('n is not greater than 10')


n is not greater than 10

In this Python pass statement example, the interpreter encounters the pass statement when n is greater than 10, and it does nothing. The program continues to execute after the indented block without any errors or interruptions.

Let’s look at what happens if we leave the if block empty without any pass statement:

n = 10
if n > 10:
    #empty code block
    print('n is not greater than 10')


Indentation error in the python interpreter

As we can see, this results in an IndentationError.

In summary, the pass statement allows you to set up the framework of your program while keeping it functional and error-free, even if the details are yet to be implemented. It’s a helpful tool for developers, enabling clear and confident code development.

Let’s take a look at how you can use pass in different areas of your code.

How to Use Pass in Loops

Loops are an essential part of programming for iterating through sequences and executing a block of code several times. The pass statement plays a crucial role in these loops when we want to ignore a specific iteration or prevent a block of code from executing.

1. ‘for’ Loops

A for loop iterates over a sequence (such as a list, tuple, or string) and executes the specified block of code for each element. The pass statement can be used with for loops to bypass or skip certain iterations.

Here’s an example:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for number in numbers:
    if number % 2 == 0:
        pass  # Ignore even numbers



In this example, the pass statement is used to ignore even numbers in the sequence. The program only prints odd numbers as output.

2. While Loops

A while loop repeatedly executes a block of code as long as a specified condition remains True. The pass statement can also be used in while loops to skip certain conditions. Here’s an example:

count = 0

while count < 10:
    count += 1
    if count % 2 != 0:
        pass  # Ignore odd numbers



In this example, the pass statement helps to ignore odd numbers in the given range. The program prints only even numbers as output.

In both scenarios, the pass statement allows us to control the execution of code and ignore specific cases within loops, making it a valuable tool in Python programming.

How to Use Pass in Conditional Statements

In this section, we’ll demonstrate the practical usage of pass within Python’s if statements and conditional statements.

1. If Statements

In Python, the pass statement is often used in if statements as a placeholder for future implementation. When an if statement contains a pass, it results in no operation (NOP).

It serves as a reminder for developers to write code at that position later on. The pass doesn’t impact the program flow. Here’s an example:

n = 10

if n > 10:
    pass  # write code later
    print("n is less than or equals to 10")


n is less than or equals to 10

In the example above, if n is greater than 10, the code encounters the pass statement, which doesn’t perform any action. This allows the developer to implement the desired code later without causing any issues during the program’s execution.

2. Conditional Statements

The pass statement can also be utilized in more complex conditional statements involving elif. It’s useful when you’re structuring your code but haven’t decided on the exact implementation for certain conditions.

Let’s look at an example with multiple conditions:

value = 50

if value < 10:
    print("Value is less than 10")
elif 10 <= value < 20:
    pass  # To be implemented later
elif 20 <= value < 30:
    print("Value is between 20 and 30")
    print("Value is equal to or greater than 30")

In this example, if the value is in the range of 10 to 20, the pass statement gets executed, indicating that the corresponding code block needs further implementation.

Like in the previous example, the pass statement doesn’t affect the program flow and acts as a placeholder for future code development.

How to Use Pass Function and Class Definitions

Pass in Class and Functions

In this section, we’ll illustrate how you can use the pass statement to define functions and classes while leaving their implementations for later.

1. Functions

In Python, functions are defined using the def keyword, followed by the function name and a pair of parentheses containing any input parameters. The function body is indented and can contain statements to be executed when the function is called.

Here’s a simple example of a Python function definition:

def greet(name):
    print(f"Hello, {name}!")

In some cases, you might want to create a placeholder function without any implementation. This is where the pass statement comes in handy.

def placeholder_function():

The pass statement essentially does nothing but allows you to create an empty function without causing any errors. In the future, you can replace the pass statement with the actual implementation.

For an example, you can check out our video on how to easily create data with Python faker library.

You can use pass statements inside the methods while still determining what parameters you want the fake data to have.

2. Classes

Similar to functions, classes are defined using the class keyword followed by the class name. As with functions, you might want to create a placeholder class definition without any implementation.

The pass statement can also be used in this case:

class PlaceholderClass:

By using the pass statement, you can define an empty class without causing any errors. Later on, you can add methods and attributes as needed.

The pass statement serves as a useful tool for creating placeholders for both functions and classes in Python, facilitating easy development and collaboration.

Handling Exceptions with Pass

In Python, exceptions are events that can be triggered when an error occurs during the execution of a program. They are often used to catch and handle errors in a controlled and clean manner.

A pass statement is sometimes used in exception handling to provide an empty block of code, allowing the program to continue executing without producing any output or performing any action.

1. Exception Class

An exception in Python is an object that is derived from the base class, BaseException. Numerous built-in exception classes are available in Python to handle common errors, such as ZeroDivisionError, FileNotFoundError, and ValueError.

Each exception class is designed to handle a specific type of error. To create a custom exception, you can define a new class that inherits from a pre-existing exception class or from the base Exception class.

Here’s an example:

class CustomError(Exception):

    raise CustomError("This is a custom exception.")
except CustomError as e:
    print(f"Caught an exception: {e}")


Caught an exception: This is a custom exception.

In this example, a new exception class called CustomError is defined by inheriting from the Exception class. The CustomError does nothing.

However, it’s necessary that the class inherits from the general exception class. This way, if anyone is checking for the base Exception class, they’ll still catch the error. In this case, the pass statement is useful in creating an empty exception child class from the parent class.

2. Abstract Base Class

An abstract base class (ABC) is a Python concept that allows a class to define a common interface. It cannot be instantiated but can be subclassed by other classes.

To create an abstract base class, use the abc.ABC class as a parent class and define the required methods with the @abstractmethod decorator.

When creating a custom exception class, you might want to use an abstract base class to define an error hierarchy. This can be particularly helpful when writing modular code or designing APIs.

Here’s an example:

from abc import ABC, abstractmethod

class BaseCustomError(Exception, ABC):

    def __str__(self):

class SpecificCustomError(BaseCustomError):
    def __str__(self):
        return "This is a specific custom exception."

    raise SpecificCustomError()
except BaseCustomError as e:
    print(f"Caught an exception: {e}")


Caught an exception: This is a specific custom exception.

In this example, BaseCustomError is an abstract base class that inherits from Exception and abc.ABC. It enforces the implementation of the str method to SpecificCustomError or any other child classes.

Since the __str__ method in the original BaseCustomError class is never called, we use a pass statement to avoid implementing any logic.

As a result, the code can run without any errors.

Pass vs Continue

The continue statement is commonly used in loops to control the flow of the program. Most people think that it is interchangeable with the pass statement. However, it is not.

The continue statement breaks out of the loop body and moves straight to the next loop iteration. No subsequent code is executed after the continue statement.

However, a pass statement doesn’t break out of the loop body, and subsequent code is still expected. For example, let’s look at the continue statement below:

for i in range(3):
    print(f'i is {i}')
    print('I will not print')


i is 0
i is 1
i is 2

Let’s replace continue with a pass statement:

for i in range(3):
    print(f'i is {i}')
    print('I will print.')


i is 0
I will print.
i is 1
I will print.
i is 2
I will print.

As we can see in the above code, the lines after the pass statement are still read and executed.

Common Errors and Solutions

The Python pass statement can often lead to some common errors if used improperly. Let’s cover some of these errors and discuss solutions to address them.

1. IndentationError

The most frequent error associated with the pass statement is the IndentationError. It occurs when the pass statement or the block of code following a control statement is not correctly indented. For example:

for i in range(5):

This will result in an IndentationError. To fix this, indent the pass statement as follows:

for i in range(5):

2. SyntaxError

Another common error with the pass statement is SyntaxError, which is caused by incorrect usage of the statement within a block of code. A common scenario is when the pass statement is used after a colon, like this:

if value > 0:
elif value < 0 pass

This will result in a SyntaxError. To resolve this, use the colon correctly after the pass statement:

if value > 0:
elif value < 0:

In conclusion, understanding the proper usage of the pass statement and being aware of potential errors will save you time and headaches. Ensure your code is correctly indented, follow Python’s syntax rules, and think about the implications of your code during testing to prevent these common errors.

Python Pass Statement in Practice

One notable use case of the pass keyword would be in handling pandas data manipulation. When processing data in a pandas.DataFrame, you might want a temporary placeholder to skip certain rows during data preprocessing:

import pandas as pd

data = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
for index, row in data.iterrows():
    if row['A'] % 2 != 0:
    else:[index, 'B'] *= 2



   A   B
0  1   4
1  2  10
2  3   6

In the example above, the pass statement helps you iterate through the DataFrame and process only the rows with even values in column ‘A’, leaving the odd values untouched.

Final Thoughts

In conclusion, the Python pass statement serves as a valuable tool in various programming scenarios. Its ability to act as a placeholder or a “do-nothing” command enables developers to structure their code effectively and avoid syntax errors.

From empty functions to future implementation placeholders, the pass statement proves its worth in maintaining code readability and aiding in the development process. As you continue to explore the vast possibilities of Python, remember to leverage the power of pass whenever the situation calls for it!

For more great Python tips, you can read through this article on Python Append List: 4 Ways To Add Elements.

Frequently Asked Questions

What is the difference between pass, break, and continue in Python?

  • pass: A null statement used as a placeholder for future code. It doesn’t affect the execution flow.
  • break: Terminates the innermost loop, stopping further iterations, and proceeds to the subsequent block of code outside the loop.
  • continue: Halts the current iteration of the loop and moves to the next iteration, skipping any remaining code in the loop body.

What is the performance cost of the pass statement?

Pass statements do not significantly impact the performance of your code as they are discarded during the byte-compile phase. However, if you use it with an if statement, it can have an effect under certain conditions.

For example, if the if statement checks a complex condition, it can affect the code’s performance. You can avoid this by designing your if-else block properly.

How does pass differ from return in Python functions?

The pass statement is a null statement used as a placeholder in functions without affecting the flow of execution. On the other hand, the return statement exits a function and returns a value to the caller. If a function doesn’t have a return statement or has it without a value, it returns None by default.

Related Posts