Python pass Statement
pass is an empty statement in Python, also called a placeholder statement.
It does nothing and merely acts as a placeholder to keep the code syntactically complete.pass It is often used in code blocks whose implementation is not yet written, or where a statement is needed at a certain position but should do nothing.
Word meaning: pass means "pass", indicating that nothing is done and it is simply skipped.
Basic syntax and parameters
pass It is a standalone statement and requires no arguments.
Syntax format
pass
Use Cases
- Empty code block: A code block is needed but no code is to be written yet.
- Function placeholder: When defining a function, its body is not implemented yet.
- Class placeholder: When defining a class, its methods are not implemented yet.
- Conditional placeholder: A conditional branch performs no operation for now.
Example
Example 1: used in an if statement
Example
The conditional branch is not handled yet
age
=
20
if
age
=
18
:
pass
TODO: age validation logic needs to be added
else
:
(
"Minor"
)
(
"Program continues"
)
Expected output:
程序继续执行
Code analysis:
- age >= 18 is True, but pass performs no operation.
- Without pass, an empty code block causes an error.
Example 2: used in a function
Example
Define an empty function
def
placeholder_function
(
)
:
pass
Calling a function
placeholder_function
(
)
(
"Function called"
)
An empty function with a condition
def
process_data
(
data
)
:
if
not
data:
pass
Data is empty, not handled yet
return
The actual processing logic
return
data.
upper
(
)
(
process_data
(
"hello"
)
)
Output: HELLO
(
process_data
(
""
)
)
Output: None
Expected output:
函数已调用
HELLO
None
When defining a function, if the body is temporarily empty, pass must be used as a placeholder.
Example 3: used in a class
Example
Define an empty class
class
EmptyClass:
pass
Instantiation
obj
=
EmptyClass
(
)
(
obj
)
Output: <main.EmptyClass object at ...>
Define an empty method in the class
class
TodoClass:
def
method1
(
self
)
:
pass
def
method2
(
self
)
:
return
"Done"
obj
=
TodoClass
(
)
(
obj.
method2
(
)
)
Output: Done
Expected output:
Empty classes or empty methods can use pass as a placeholder, with the actual functionality implemented later.
Example 4: used in a loop
Example
Iterate but do nothing
for
i
in
range
(
5
)
:
pass
Not handled for now
(
"Loop complete"
)
Used together with a condition
for
i
in
range
(
10
)
:
if
i %
2
==
0
:
pass
Even numbers are not handled
else
:
(
i
,
end
=
" "
)
Output: 1 3 5 7 9
Expected output:
循环完成
1 3 5 7 9
pass It can also be used as a placeholder in loops.
Python3 Conditional Control