Skip to main content
 首页 » 编程设计

python之为什么 python 在 `pass` 之后继续评估代码

2025年05月04日11pander-it

我在python中发现了一段有趣的代码:

def x(cond): 
    if cond: 
        pass 
        print('Still running!') 
 
x(True) 

我希望这不会打印任何东西,但它会打印 Still running!。这里发生了什么?

请您参考如下方法:

根据 Python 文档:

pass is a null operation — when it is executed, nothing happens.

来源 - https://docs.python.org/3.5/reference/simple_stmts.html#pass

因此,pass 不会做任何事情,pass 之后的所有语句仍将被执行。

另一种思考方式是 pass 等同于任何伪语句:

def x(cond): 
    if cond: 
        "dummy statement" 
        print('Still running!')