Оператор pass в Python
Оператор pass — это пустой оператор, который можно использовать в качестве заглушки для будущего кода. Предположим, у нас есть цикл или функция, которая еще не определена, но мы ее определим в будущем. В таких случаях мы можем использовать оператор pass.
Синтаксис оператора pass:
Рассмотрим пример использования оператора pass:
Обратите внимание, что мы использовали оператор pass внутри конструкции if. Но ничего не происходит при выполнении оператора pass (получается ситуация NOP, сокр. от «No Operation»). Просто выполняется следующий код.
Теперь давайте выполним тот же код, но вместо pass напишем комментарий:
Мы получим сообщение об ошибке: IndentationError: expected an indented block
Примечание: Разница между комментарием и оператором pass в Python заключается в том, что хотя интерпретатор полностью игнорирует комментарий, оператор pass не игнорируется.
Также мы можем использовать оператор pass в функции или классе. Например, функция:
Зачем нужен оператор pass?
![]()
Синтаксис Python требует, чтобы у некоторых операторов обязательно было тело: класс, функция, условие и т. д. Но иногда необходимо, чтобы там ничего не выполнялось. В таком случае подставляют pass .
Практические кейсы использования:
Создание пользовательского класса на основе другого
Актуально там, где имя класса несёт смысл (исключения, модели БД и т. п.):
What is a pass in Python?
In this article, we will show you what is a pass statement in Python and how to use it in python programming.
Python pass statement
Python pass is a null statement offered by Python to ignore a block of code we do not want to execute. If a function, class, or loop must be coded and performed in the future, the python pass statement instructs the Python Interpreter to ignore that function, class, or loop while the program is running.
Nothing happens when the pass statement is performed, but you avoid an error when empty code is not allowed.
Loops, function definitions, class definitions, and if statements cannot allow any empty code.
Syntax
Using ‘pass’ statement in empty function
We can use the pass statement in empty functions
Syntax
Using ‘pass’ statement in empty class
We can use the pass statement in an empty class
Syntax
Using ‘pass’ Statement in For Loop
When the user is unsure what to code inside the for loop, the pass statement can be used.
Assume we have a loop or an if-else expression that does not need to be filled right now but will in the future. An empty body for the pass keyword would be syntactically incorrect. The Python interpreter would display an error message requesting that the space be filled. As a result, we use the pass statement to create a code block that does nothing.
Algorithm (Steps)
Following are the Algorithm/steps to be followed to perform the desired task −
Create a variable to store the input list.
Use the for loop, to traverse through each element of the list.
Use the if conditional statement and % operator(returns the remainder) to check whether the list element is an even number or not.
If the list element is even, then just pass leaving an empty if block.
Else printing the list element (which is odd).
The following program returns all the odd numbers from the input list and just pass leaving an empty if block if the element is an even number −
Example
Output
On executing, the above program will generate the following output −
We took a list with some random elements and used the for loop to traverse through all of the list’s elements. If the element is divisible by 2, no action is required, and the pass statement that we wrote executes.
Using ‘pass’ Statement with Conditional Statements
We can use the pass statement with conditional statements. Let us see an example where we use the pass statement with an if conditional statement.
Algorithm (Steps)
Following are the Algorithm/steps to be followed to perform the desired task −
Create a variable to store the first number.
Create another variable to store the second number.
Use the if conditional statement to check whether the number_1 is less than number_2.
Just pass leaving an empty if block, if the condition is true.
Else print some random text.
The following program checks whether number_1 is less than number_2 using if conditional statement and pass if the condition is true −
Output
On executing, the above program will generate the following output −
How is Python pass different from continue statements?
Example
Most people get confused with the pass and continue statements. Let us see the difference between them in a code for better understanding.
The pass statement has no effect. The pass statement is used when designing a method, function, class, or loop code that you do not want to implement right away. It will execute the method, and if the condition is met, it will ignore the code and go to the next line of code.
The continue statement, on the other hand, skips all remaining statements in the loop and returns control to the top. If the loop’s condition is met, that condition is skipped and the next iteration is performed.
Example of pass statement
Output
On executing, the above program will generate the following output −
Example of continue statement
Output
On executing, the above program will generate the following output −
Conclusion
This article covered all of the scenarios in which the pass statement is used. Using the same example, we also learned how the pass statement differs from the continue statement.
Оператор Python pass
Оператор передачи Python pass используется для создания пустых блоков кода и пустых функций.
Примеры операторов передачи Python
Давайте посмотрим на несколько примеров с использованием pass.
1. инструкция pass в блоке кода
Допустим, нам нужно написать функцию для удаления всех четных чисел из списка. В этом случае мы будем использовать цикл for для обхода чисел в списке.
Если число делится на 2, то ничего не делаем. В противном случае мы добавляем его во временный список. Наконец, верните вызывающему абоненту временный список, содержащий только нечетные числа.
Python не поддерживает пустые блоки кода. Таким образом, мы можем использовать здесь оператор pass для отсутствия операции в блоке if-condition.
Здесь нам не нужны никакие операции в блоке if-condition. Итак, мы использовали оператор pass для бездействия.
2. инструкция pass для пустой функции
В Python нет концепции абстрактных функций. Если нам нужно определить пустую функцию, мы не можем написать ее так.
Выход: IndentationError: ожидается блок с отступом
Мы можем использовать оператор pass для определения пустой функции. У функции будет инструкция, но она ничего не сделает.
Можно ли иметь в функции несколько операторов?
Да, у нас может быть несколько операторов прохода в функции или блоке кода. Это потому, что оператор pass не завершает функцию. Его единственная работа — предоставить пустой оператор.
Зачем нужен?
- Оператор передачи Python очень полезен при определении пустой функции или пустого блока кода.
- Наиболее важное использование оператора pass — создать контракт для классов и функций, которые мы хотим реализовать позже. Например, мы можем определить модуль Python следующим образом:

Мы можем приступить к реализации. Сторонний код знает функции и методы, которые мы будем реализовывать, поэтому они могут продолжить их реализацию.