我在python中发现了一段有趣的代码:
def x(cond):
if cond:
pass
print('Still running!')
x(True)
Run Code Online (Sandbox Code Playgroud)
我希望这不打印任何东西,但它打印Still running!.这里发生了什么?
根据Python文档:
pass是一个空操作 - 当它被执行时,没有任何反应.
来源 - https://docs.python.org/3.5/reference/simple_stmts.html#pass
因此,pass不执行任何操作,之后的所有语句pass仍将执行.
另一种思考方式pass是相当于任何虚拟语句:
def x(cond):
if cond:
"dummy statement"
print('Still running!')
Run Code Online (Sandbox Code Playgroud)