剖析Python缩进之谜

2024-04-18 03:09:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: to错误stdinline语句fileprintsyntax
3条回答

我想出现这个错误是因为pythonshell不支持它。它希望你一次只做一件事。!我在python2.7shell中也做了同样的事情,它说:

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

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

默认的pythonshell对于输入工作正常,但它确实不理解从剪贴板粘贴。真正的解决方案是安装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]: 

您需要在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块中

相关问题 更多 >