Python 简明教程
Python - pass Statement
Python pass Statement
Python pass 语句用于当语法需要一个语句但你不想执行任何命令或代码时。它是一个空语句,这意味着它执行时没有任何事情发生。这在稍后会添加一段代码但需要一个占位符以确保程序在没有错误的情况下运行的地方也非常有用。
Python pass statement is used when a statement is required syntactically but you do not want any command or code to execute. It is a null which means nothing happens when it executes. This is also useful in places where piece of code will be added later, but a placeholder is required to ensure the program runs without errors.
例如,在一个函数或类的定义中,其中实现尚未写入,可以使用 pass 语句来避免 SyntaxError。此外,它还可以用作 for and while 循环等控制流语句中的占位符。
For instance, in a function or class definition where the implementation is yet to be written, pass statement can be used to avoid the SyntaxError. Additionally, it can also serve as a placeholder in control flow statements like for and while loops.
Syntax of pass Statement
以下是 Python pass 语句的语法 -
Following is the syntax of Python pass statement −
pass
Example of pass Statement
下面的代码展示了如何在 Python 中使用 pass 语句 -
The following code shows how you can use the pass statement in Python −
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")
当执行以上代码时,它会产生以下 output -
When the above code is executed, it produces the following output −
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
Dumpy Infinite Loop with pass Statement
这已经足够简单到可以使用 Python 中的 pass 语句创建无限 loop 。
This is simple enough to create an infinite loop using pass statement in Python.
Example
如果你想编写一个每次遍历时都不做任何事儿的无限循环,请按如下所示进行操作 -
If you want to code an infinite loop that does nothing each time through, do it as shown below −
while True: pass
# Type Ctrl-C to stop
因为循环体只是一个空语句,所以 Python 会一直停在这个循环中。
Because the body of the loop is just an empty statement, Python gets stuck in this loop.
Using Ellipses (…) as pass Statement Alternative
Python 3.X 允许使用省略号(编码为连续三个点 …)代替 pass 语句。两者都充当将来要编写的代码的占位符。
Python 3.X allows ellipses (coded as three consecutive dots …) to be used in place of pass statement. Both serve as placeholders for code that are going to be written later.
Example
例如,如果我们 create a function 没有特别为以后要填写的代码执行任何操作,那么我们可以使用 …
For example if we create a function which does not do anything especially for code to be filled in later, then we can make use of …
def func1():
# Alternative to pass
...
# Works on same line too
def func2(): ...
# Does nothing if called
func1()
func2()