Python 缩进之谜

Python indentation mystery

为什么会出现以下错误?最后一个 print 语句不应该是 while 循环的一部分。

>>> while n>= 0:
...     n = n-1
...     print(n)
... print ("TO A!!")
  File "<stdin>", line 4
    print ("TO A!!")
        ^
SyntaxError: invalid syntax

您需要在 while 循环后按 enter 以退出循环

>>> n = 3
>>> while n>=0:
...     n = n-1
...     print (n)
...                         # Press enter here
2
1
0
-1
>>> print ("To A!!")
To A!!

注意:- ... 表示您仍在 while 区块

默认的 python shell 可以正常输入,但它真的不理解从剪贴板粘贴。真正的解决方案是安装 ipython,它是 python 的高级 shell,具有许多优点:

% ipython3
Python 3.4.2 (default, Oct  8 2014, 13:08:17) 
Type "copyright", "credits" or "license" for more information.

IPython 2.3.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: n = 5

In [2]: while n >= 0:
   ...:     n = n-1
   ...:     print(n)
   ...: print ("TO A!!")
   ...: 
4
3
2
1
0
-1
TO A!!

In [3]: 

我猜是因为 python shell 不支持该错误。它要你一次做一件事。!我在 python 2.7 shell 中做了同样的事情,它说:

File "<pyshell#4>", line 4
    print 'to all'
                 ^
IndentationError: unindent does not match any outer indentation level

当我在 python 3.4 shell 中做同样的事情时,它说:unexpected indent.