Skip to main content
 首页 » 编程设计

python之为什么在这个 if/else 中执行 pass 语句

2025年05月04日18zengkefu

当我在 Debug模式下运行以下 if/else 时

if True: 
  print 'here' 
else: 
  print 'there' 
  pass  # breakpoint here 

调试器在 pass 语句处停止。为什么要执行 pass 语句?我知道 pass 是无关紧要的,但它在 else 中。

我在 Pycharm 2.7.3 上运行 python 2.7.5

更新

如果 pass 语句是程序的最后一行,并且上面有一个断点,调试器将在该 pass 语句处停止。我知道它已停止,因为我可以看到当前的堆栈跟踪和变量。

但是如果 pass 不是最后一行,调试器不会停在那里。

请您参考如下方法:

调试器不会在 pass 语句处中断。您可以通过在其后添加语句来验证这一点:

$ cat test.py 
if True: 
  print 'here' 
else: 
  print 'there' 
  pass  # breakpoint here 
print 'done' 
$ python -m pdb test.py 
> test.py(1)<module>() 
-> if True: 
(Pdb++) list 
  1  -> if True: 
  2       print 'here' 
  3     else: 
  4       print 'there' 
  5       pass  # breakpoint here 
  6     print 'done' 
[EOF] 
(Pdb++) break 5 
Breakpoint 1 at test.py:5 
(Pdb++) continue 
here 
done 
The program finished and will be restarted 

调试器可能出现中断,因为它是文件中的最后一行?