在哪些情况下我可以在 python 中使用缩进?

In which cases can I use indentations in python?

我正在阅读 Python Language reference

lexical analysis page

Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At the beginning of each logical line, the line’s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated.

在这里,它表示在一行上添加缩进只会将与 INDENT 关联的值添加到缩进跟踪堆栈中。


所以我尝试做 python 等效于 C++ 片段

int x = 23;
{
    int y = 13;
}
int z = 2*x;

使用这个 python 片段

x = 23
    y = 13
z = 2*x

但是使 python 运行 此代码生成以下错误:

    y = 13
IndentationError: unexpected indent

所以上面的规则并不总是适用,我想知道

"At the beginning of each logical line, the line’s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated."

所以在这里它告诉你所有关于何时生成缩进标记的信息。现在您还需要知道只有关键字 class、def、if、for、while 等可以让您拥有额外的当前缩进标记。

"when I can use the indentation, other than the general cases like function and class definitions"。 -> 从不。

注意:换行不算作缩进标记。所以:

>>> a = [1, 2, \  # \ is breaking line.
        3]

是可能的,它在技术上不算作缩进,因为它是相同的 python 行。函数参数相同:

>>> a = np.array([0,1],
                 dtype=float)

我认为缩进最重要的用法是在循环中。因为 python 没有像 Matlab 中那样的 end for 循环,所以具有正确缩进的行在循环中。