为什么要这样:继续处理需要通行证? [英] Why is this else: pass needed for processing to continue?
问题描述
有人可以解释为什么要执行其余的代码(最后的print 'processing...
语句)需要以下所示的else: pass
吗?请注意,else
中的print
只是放在那里,所以我可以确定执行确实采用了该路径.
Can someone explain why the else: pass
shown below is needed in order for the rest of the code (the final print 'processing...
statement) to be executed? Note the print
in the else
was put there just so I could tell that execution was indeed taking that path.
由于else
中的代码不执行任何操作,因此似乎不执行continue
时应该发生这种情况.但是,如果我不使用else
,则当条件为False时-目录中存在扩展名为 do 的文件时,似乎不会执行for
循环中的任何内容对我来说没有意义.文档说continue
继续最近的封闭循环的下一个循环",很好,但是如果未执行,则处理不应该继续执行下一条语句吗?
It seems like that should happen whenever the continue
isn't executed since code in the else
does nothing. However, if I leave the else
out, nothing further in the for
loop appears to be executed when the condition is False -- when files with the extension do exist in the directory -- which doesn't make sense to me. The docs say continue
"continues with the next cycle of the nearest enclosing loop", fine, but if one is not executed, shouldn't processing proceed to the next statement?
import os
source_dir = r'C:\Downloads'
ext = '.mp3'
for dirName, subdirList, fileList in os.walk(source_dir):
if not any(os.path.splitext(fileName)[1].lower() == ext for fileName in fileList):
print ' skipping "{}"'.format(dirName)
continue
else: # why is this clause needed to continue this iteration of a loop?
print 'contains "{}"'.format(dirName)
pass
print 'processing "{}" which has "{}" files'.format(dirName, ext)
已解决的谜题
看似奇怪的行为是由于缩进问题所致,在上面的代码中也不可见,通常在我的文本编辑器中也不可见.原来,最后一个print
语句的缩进是3个空格,然后是一个制表符,这使其看起来与else
对齐,但是实际上,如果存在,它要么跟随else
中的pass
,或跟随if
的第一部分中的continue
.显然使我非常困惑.
The seemingly strange behavior was due to an indentation problem which is not visible in the code above nor normally in my text editor. It turned out that the last print
statement was indented by 3 spaces then a tab, which makes it appear to align with the else
, but in fact it either follows the pass
in the else
if it's there, or follows the continue
in the first part of the if
. Obviously confusing me a great deal.
这是我的文本编辑器中代码的屏幕截图,其中的显示空间/标签"选项处于打开状态.红点表示空格,右红色吉尔梅特字符(»
)表示制表符:
Here's a screenshot of the code in my text editor with its "show space/tabs" option turned on. The red dots represent spaces and the red right guillemets (»
) represents a tab character:
推荐答案
我要回答自己的问题并最终接受.所描述的看似奇怪的行为是由一个细微的缩进问题引起的,该问题的可能性首先由用户@delnan引起了我的注意.因为它是不可见的,所以最初我不认为是这种情况,但最终经过更多调查后才发现.详细信息已添加到我的问题的末尾.
I'm going to answer my own question and eventually accept it. The seemingly odd behavior described was caused by an subtle indention problem, the possibility of which was first brought to my attention by user @delnan. Because it was invisible, initially I didn't think it could be the case, but eventually found it after more investigation. The details of which have been added to the end of my question.
这篇关于为什么要这样:继续处理需要通行证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!