tsh*_*tsh 4 python syntax indentation
为什么以下代码在Python控制台(在我的情况下为2.6.5版本)中产生缩进错误?我确信以下是有效的代码:
if True:
print '1'
print 'indentation error on this line'
Run Code Online (Sandbox Code Playgroud)
如果我在if块和最后一个打印之间插入一个空行,则错误消失:
if True:
print '1'
print 'no error here'
Run Code Online (Sandbox Code Playgroud)
我有点困惑,从我看来,空白(或只是白色空间)线条的文档应该没有任何区别.任何提示?
问题是由于使用了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
>>>
Run Code Online (Sandbox Code Playgroud)
控制台接受单个指令(多行,如果它是的定义function; if,for,while,...),在一次执行.
这里:2条说明
_______________
if True: # instruction 1 |
print '1' # _______________|
print 'indentation error on this line' # instruction 2 |
----------------
Run Code Online (Sandbox Code Playgroud)
这里:2条指令由blanck线分隔; 一个blanck行就像你点击enter =>执行一条指令
if True:
print '1' # instruction 1
[enter]
print 'no error here' # instruction 1
Run Code Online (Sandbox Code Playgroud)