它或多或少是硬连接到lexer中的-任何跟在:后面的都被认为是块语句,如果之后有新行,那么它必须至少缩进一个空格。在
PEP 8对Python的正式样式指南提供了一些清晰的说明。简而言之,缩进使代码更具可读性。在The indentation levels of consecutive lines are used to generate
INDENT and DEDENT tokens, using a stack, as follows.
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. If it is smaller, it must be one of the numbers occurring
on the stack; all numbers on the stack that are larger are popped off,
and for each number popped off a DEDENT token is generated. At the end
of the file, a DEDENT token is generated for each number remaining on
the stack that is larger than zero.
sinepython使用堆栈来保证特定块的缩进级别是一致的,没有缩进将破坏lexer,并导致Python代码不被解释。在
lexer的灵活性也允许这样做(但不要这样做,否则Python程序员会一直鄙视你,直到最后):def foo(n):
for i in range(0, 10):
print i, i+1
i = 0
while i < 10:
print i
print i - 1
print i + 1
哦,如果你有太多的嵌套语句,也许你应该考虑重构你的代码,使其读得更清楚,并减少代码的复杂性?在