Python 缩进语义

Python indentation semantics

我只是有一个非常简单的问题,只是需要确认我明白了。

假设我们有以下 Python 代码片段:

x = 0
if x == 5:
    print 'x is equal to 5'
else:
    print 'x is not equal to 5'

print 'program done'

如果我们缩进语句 print 'program done' 如下:

else:
    print 'x is not equal to 5'
    print 'program done'

在这种情况下,print 'program done' 是否会成为与 else 关联的块代码的一部分?

来自Python Docs

Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.

所以,是的,它将属于 else 区块。