python - 功能缩进不按预期工作

标签 python python-2.7

<分区>

我发现了一些对我来说没有意义的东西。我希望有人能解释一下。

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 ,当被 P​​ython 解释时,它最多扩展到 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 中,当您选择文本时,空格显示为暗点,制表符显示为一行:

Sublime Text editor with code from OP selected; the tab on the return line is visible as a line, spaces are shown as subtle grey dots

关于python - 功能缩进不按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28021409/

相关文章:

python-2.7 - 选择 Python 后立即选择选项菜单

python-2.7 - 从数据框中选择具有非零值的列

python - 从 unittest 测试调用时 argparse 失败

python - 使用python分析抛硬币统计

python - pd.read_csv - 忽略前 N 行

c++ - Python 将输入重定向到子进程

python - Openslide python导入错误

python - 如何使用python一一打印原始行和重复行

python - Django 更新整个对象(行)

python - 使用 nltk 访问 python 中的同义词时出错?