Python pass 语句
当语法上需要某个语句,但您不希望执行任何命令或代码时,将使用 Python pass 语句。它是一个 null,这意味着它在执行时不会发生任何事情。这在稍后将添加代码段的地方也很有用,但需要一个占位符来确保程序运行没有错误。
例如,在尚未编写实现的函数或类定义中,可以使用 pass 语句来避免 SyntaxError。此外,它还可以用作控制流语句(如 for 和 while 循环)中的占位符。
pass 语句的语法
以下是 Python pass 语句的语法 -
pass
pass 语句示例
以下代码显示了如何在 Python 中使用 pass 语句 -
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")
执行上述代码时,它会生成以下输出 -
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
带有 pass 语句的 Dumpy 无限循环
这很简单,可以在 Python 中使用 pass 语句创建无限循环。
例如果您想编写一个每次都不执行任何操作的无限循环,请执行以下操作 -
while True: pass
# Type Ctrl-C to stop
因为循环的主体只是一个空语句,所以 Python 会卡在这个循环中。
使用省略号 (...) 作为 pass 语句替代
Python 3.X 允许使用省略号(编码为三个连续的点...)来代替 pass 语句。两者都用作稍后将要编写的代码的占位符。
例例如,如果我们创建一个函数,它不做任何事情,特别是对于稍后要填充的代码,那么我们可以使用 ...
def func1():
# Alternative to pass
...
# Works on same line too
def func2(): ...
# Does nothing if called
func1()
func2()