我发现了一些对我来说没有意义的东西。我希望有人能解释一下。
def test(word):
total = 0
for l in word:
print l
test('python')
结果是 'p y t h o n'(每个字母单独占一行)。
def test(word):
total = 0
for l in word:
print l
return total
test('python')
结果只是'p'。
添加 return
语句怎么会有这种效果?两个代码块不应该做同样的事情吗?这是否意味着它只经过一次 for 循环,然后执行 return
语句?
获得所见行为的唯一方法是将 return total
缩进为 for
循环的一部分。如果它在您的编辑器中看起来不是这样,那是因为您在return
行中使用了 TAB 字符:
>>> code_as_posted = '''\
... def test(word):
... total = 0
... for l in word:
... print l
... return total
... '''
>>> code_as_posted.splitlines()[-1]
'\treturn total'
看到那里的 \t
字符转义了吗?那是一个 tab character ,当被 Python 解释时,它最多扩展到 8 个空格;见Indentation在 Python 引用文档中:
First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation.
由于 return
提早退出循环,您只会看到打印的 'p'
字符。
您的编辑器和 Stack Overflow Markdown 实现都将制表符显示为 四个 空格,因此很难在此处发现此特定错误。使用 -tt
command line switch 运行 Python在混合使用制表符和空格时引发异常。
您需要将编辑器配置为将制表符扩展为空格,或者只使用制表符。不要混用这两种风格。 Python Style Guide强烈建议您仅使用空格:
Spaces are the preferred indentation method.
Tabs should be used solely to remain consistent with code that is already indented with tabs.
许多编辑器还可以使选项卡明确可见。在 Sublime Text 中,当您选择文本时,空格显示为暗点,制表符显示为一行: