• Articles
  • Tutorials
  • Interview Questions

What is Pass in Python? Definition, Usage, & Examples

The Python pass statement acts as a hall pass, similar to the ones used in school, enabling you to bypass a section of code without encountering any issues. In this blog, we’ll explore the purpose of this fundamental keyword and its applications, offering a clear understanding of its role in Python programming.

Table of Contents:

Check out this YouTube video to learn about Python:

What is pass in Python?

In Python, the `pass` statement is like a temporary placeholder that programmers use when they want to delay writing specific parts of their code. It’s often used in situations where they need to create a function, loop, or if-statement but haven’t yet figured out exactly what should go inside. This statement allows the program to run without any errors even if some parts are incomplete.

What is pass in Python

For example, if a programmer wants to create a function but hasn’t decided what the function should do, they can use the `pass` statement to let the Python interpreter know that it should simply move on to the next part of the code. Even though the `pass` statement doesn’t do anything, it’s essential for indicating that the programmer plans to add more code there later on.

The syntax of Python pass statement is shown below

pass

To make you understand it more clearly, here’s a simple example demonstrating the creation of empty function using pass keyword:

#Creating an empty function
def empty_function():
    pass  # This function will not perform any operation

In this example, we have created a function which will not perform any operation when the program is executed. This will give an empty output.

Here is another example, where we are creating an empty class using pass keyword-

# Creating an empty class using pass
class EmptyClass:
    pass  # This class doesn't have any methods or attributes yet

In this example, the class “EmptyClass” does not perform any operation but it can be utilized later for writing and implementing some code.

In both of the above examples, the pass keyword is utilized as a placeholder, indicating that the block, function, or class doesn’t have any specific code implementation at that point.

Let’s see another example

fruits = ["apple", "banana", "cherry", "date", "fig"]
for fruit in fruits:
    if fruit == "date":
        pass  # Placeholder for handling "date" later
    else:
        print("I like", fruit)

This Python code runs through a list of fruits, such as apple, banana, cherry, date, and fig. The program checks each fruit in the list and prints “I like” followed by the name of the fruit, except for “date.” When the code encounters “date,” it doesn’t print anything but instead waits for some additional instructions or actions to be defined for the “date” fruit later in the program. This can be considered as a placeholder, indicating that there will be specific handling for the “date” fruit, though it is not yet implemented at this stage in the code.

To learn this latest programming language, sign up for Intellipaat’s trending Python Course and become proficient in it!

Why use pass in Python?

In Python, the `pass` statement is used as a placeholder when a statement is required syntactically but no action is necessary or desired. It essentially serves as a no-operation statement. 

Here’s why you would use `pass` in Python:

1. Placeholder in Development: Often, when you are working on creating a code structure, you might want to outline the overall structure before implementing the details. In such situations, you can use `pass` as a placeholder for future code to be added.
2. Empty Classes or Functions: When defining a class or function that you plan to implement later, you can use `pass` to indicate that there is no code inside the class or function at the moment, but you intend to add it in the future.
3. Handling Conditional Blocks: Sometimes, in conditional blocks i.e. `if`, `else`, or `elif`, there might be a block that doesn’t do anything. In such cases, using `pass` allows the program to maintain its syntactical structure without causing any side effects.

In simple words, the `pass` statement helps you to create valid syntactical structures in your code without executing any specific action. It’s useful for situations where you need a placeholder for future code implementation or for cases where an empty block is necessary to maintain the structure of the code.

Why Use pass in Python

Suppose you are creating a class named “MyClass”and a method inside the class named”my_method” . You have created the method but want to define it later. Now here, you can use the pass statement as a placeholder: Here is the code for this example:

class MyClass:
    def my_method(self):
        pass  # Placeholder for method implementation
# Other code

In this example, there is a class named MyClass containing a method called my_method. The method my_method doesn’t have any specific implementation and is represented by the pass keyword. This means that the method is a placeholder for potential code that will be added later. This allows the program to run without issues even if the method is not fully defined. 

There will be no output of this program at the same time there will be no error either.

Get 100% Hike!

Master Most in Demand Skills Now !

Example of pass in Python

To understand the concept more clearly, we will see some examples demonstrating how to create a class or a function containing the pass keyword in Python.

class MyClass:
    def My_method(self):
        pass  # Placeholder for method implementation
    def another_method(self, name):
        print(f"Hello, {name}! Welcome to the MyClass.")
# Other code
# Instantiate the class and call the methods
obj = MyClass()
obj.another_method("John")
obj.My_method()

In this example, there’s a Python class called `MyClass` that contains two methods. The first method, `my_method`, has the `pass` statement. It acts as a placeholder for some future code implementation. The second method, `another_method`, takes a parameter `name` and prints a greeting message using the provided name. An instance of the class is created i.e. `obj = MyClass()`. The method `another_method` is called on this instance, passing the name “John” as an argument. This results in the output “Hello, John! Welcome to the MyClass.”

Output:

Hello, John! Welcome to the MyClass.

Here is another example, demonstrating the use of pass:

def check_value(x):
    if x > 0:
        print("Value is positive")
    elif x < 0:
        print("Value is negative")
    else:
        pass  # Placeholder for handling the case when the value is 0
# Calling the function with different values
check_value(10)
check_value(-5)
check_value(0)

In this example, the method ‘check_value’ checks whether a number ‘x’ is positive, negative, or zero. If ‘x’ is positive, the function prints “Value is positive”. Similarly, if ‘x’ is negative, it prints “Value is negative”. However, when ‘x’ equals 0, the function employs the ‘pass’ statement, indicating that at this moment, no specific action is needed. This feature helps maintain the structure of the function. The example showcases how the function manages various scenarios using the ‘pass’ statement as a placeholder within the if-else block.

This program will give the following output:

Value is positive
Value is negative

Want to know about the real-world uses of Python? Read our detailed blog on Python Applications now.

Usage of pass in Python

Without writing the code, it is impossible to define a function, class, or loop in the Python programming language. An error is thrown as a result. Thus, using the pass statement is useful when you want to have empty code but don’t want the error to be raised. pass acts as a placeholder for any future code that you might create. When the pass statement is used, no operation or NOP happens.

Usage of pass in Python

The pass keyword can be used inside Python functions, classes, loops, and conditional statements. We will see its usage inside all of these blocks one by one.

1. Use of pass Inside Python Function

Here is an example showcasing the use of the pass keyword within a Python function:

def placeholder_function():
    pass  # This function is a placeholder for future implementation
def calculate_square(numbers):
    squared_numbers = [num ** 2 for num in numbers]
    print(f"The squared numbers are: {squared_numbers}")
# Calling the functions
placeholder_function()
calculate_square([1, 2, 3, 4, 5])

In this example, the placeholder_function is designated for future implementation and contains the pass statement. On the other hand, the calculate_square function takes a list of numbers as input, calculates the square of each number, and prints the squared numbers. 

The output of this program will be:

The squared numbers are: [1, 4, 9, 16, 25]

2. Use of pass in Python Classes

Here’s an example demonstrating the use of the pass keyword within Python Classes:

class Calculator:
    def add_numbers(self, num1, num2):
        # Adding the numbers and printing the sum
        print(f"The sum of {num1} and {num2} is {num1 + num2}.")
    def subtract_numbers(self, num1, num2):
        #  Subtracting the numbers and printing the difference
        print(f"The difference between {num1} and {num2} is {num1 - num2}.")
    def multiply_numbers(self, num1, num2):
        product = num1 * num2
        print(f"The product of {num1} and {num2} is {product}.")
    def divide_numbers(self, num1, num2):
        try:
            division = num1 / num2
            print(f"The division of {num1} and {num2} is {division}.")
        except ZeroDivisionError:
            pass
# Instantiating the class
calc = Calculator()
# Performing calculations
calc.add_numbers(5, 3)
calc.subtract_numbers(5, 3)
calc.multiply_numbers(5, 3)
calc.divide_numbers(6, 2)

In this example, the divide_numbers method inside the Calculator class, uses the pass statement within the except block, which allows the program to handle the ZeroDivisionError silently without printing any specific error message. This implementation ensures that the program does not terminate abruptly when attempting to divide by zero and instead continues to execute the rest of the code.

The output of this program will be:

The sum of 5 and 3 is 8.
The difference between 5 and 3 is 2.
The product of 5 and 3 is 15.
The division of 6 and 2 is 3.0.

However, if we change the numbers in divide_numbers method and make the denominator zero, then the output would be:

The sum of 5 and 3 is 8.
The difference between 5 and 3 is 2.
The product of 5 and 3 is 15.

3. Use of pass in Python Conditional Statement

Here is an example demonstrating the use of the pass keyword within a Python conditional statement.

x = int(input("Enter the value of x: "))
if x < 10:
    pass  # This block is intentionally left empty
else:
    print("x is greater than or equal to 10")

In this program, the user is prompted to enter the value of x using the input() function. After receiving the value of x, the program checks whether it is less than 10 or not, and based on the condition, it either executes the pass statement or the print statement accordingly.

If the user enters any number less than x, let’s assume 9, the output will be:

Enter the value of x: 9

If any number greater or equal to 10 is entered, then the following output will be displayed:

Enter the value of x: 11
x is greater than or equal to 10

4. Use of pass in Python Loop

Let’s see a simple example explaining how the pass keyword works in a Python loop.

numbers = [2,3,4,6,8,10]
for number in numbers:
    if number == 3:
        pass
        print("This is a pass block")
    print("Current Number:", number)
print("All numbers processed")

Here, in this example, a variable named “numbers” contains a list of numbers. Every number in the list is iterated using the for loop. The pass statement is encountered when the value equals 3, enabling the script to skip the code inside the if block and continue with the loop instead. The phrase “This is a pass block” is then printed by the script. The script then prints “Current Number” with the appropriate number. Once the loop is finished, it prints “All numbers processed” to show that every number in the list has been looked at. 

The output of this program will look as follows:

Output:

Current Number: 2 
This is a pass block 
Current Number: 3 
Current Number: 4 
Current Number: 6 
Current Number: 8 
Current Number: 10 
All numbers processed

Prepare yourself for the industry by going through Python Interview Questions and Answers now!

Conclusion

The ‘pass’ statement in Python may seem small, but it packs a big punch in various coding scenarios. Its simplicity is its strength, and you’ve now discovered how it serves as a versatile tool for placeholders, code structure, and more. As you continue your Python journey, remember that even the most unassuming commands can have a significant impact on your code. Happy coding!

If you have any doubts, you can reach out to us on our Python Community!

Course Schedule

Name Date Details
Data Scientist Course 04 May 2024(Sat-Sun) Weekend Batch
View Details
Data Scientist Course 11 May 2024(Sat-Sun) Weekend Batch
View Details
Data Scientist Course 18 May 2024(Sat-Sun) Weekend Batch
View Details

Executive-Post-Graduate-Certification-in-Data-Science-Artificial-Intelligence-IITR.png