Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python pass Statement

Python pass Statement

Python3 Conditional Statements Python3 Conditional Control


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


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

:

   

print

(

"Minor"

)

print

(

"Program continues"

)

Expected output:

程序继续执行

Code analysis:

  1. age >= 18 is True, but pass performs no operation.
  2. 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

(

)

print

(

"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

(

)

print

(

process_data

(

"hello"

)

)

 

Output: HELLO

print

(

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

(

)

print

(

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

(

)

print

(

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

print

(

"Loop complete"

)

Used together with a condition

for

i

in

range

(

10

)

:

   

if

i %

2

==

0

:

       

pass

 

Even numbers are not handled

   

else

:

       

print

(

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 Statements Python3 Conditional Control