基本的Python缩进/缩进取消问题

4 投票
2 回答
1071 浏览
提问于 2025-04-16 19:16

为什么下面的代码在我的Python控制台(我用的是2.6.5版本)会出现缩进错误呢?我一直以为这段代码是有效的:

if True:
    print '1'
print 'indentation error on this line'

如果我在if语句块和最后的print之间插入一个空行,错误就消失了:

if True:
    print '1'

print 'no error here'

我有点困惑,从文档上看,空行(或者只有空格的行)似乎不应该有任何影响。有没有什么提示呢?

2 个回答

5

控制台一次只能接受一条指令(如果是定义一个function,或者ifforwhile等,可以是多行)。

这里有:2条指令

                                          _______________
if True:                                # instruction 1  |
    print '1'                           # _______________|
print 'indentation error on this line'  # instruction 2  |
                                          ----------------

这里有:2条指令,中间用一个空行分开;空行就像你按下回车键一样 => 每次执行一条指令

if True:
    print '1'         # instruction 1
[enter]
print 'no error here' # instruction 1
5

这个问题是因为使用了Python的控制台,而不是Python语言本身。如果你把所有代码放在一个方法里,就能正常运行。

举个例子:

>>> if True:
...     print '1'
... print 'indentation error on this line'
  File "<stdin>", line 3
    print 'indentation error on this line'
        ^
SyntaxError: invalid syntax
>>> def test():
...     if True:
...         print '1'
...     print 'no indentation error on this line'
... 
>>> test()
1
no indentation error on this line
>>> 

撰写回答