【问题标题】:Python indentation mysteryPython缩进之谜
【发布时间】:2015-04-16 00:17:54
【问题描述】:

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

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

【问题讨论】:

  • @KasraAD 这不是问题的原因,它仍然是有效的语法。
  • @KasraAD 这就是解释器的显示方式 - '... ' 是继续提示
  • 是的,我只是想念它在终端:D
  • @Juergen,空格不影响语句。 print("string") 和 print("string") 都可以。答案实际上与下面有人提到的有关。在 shell 上,一次只能运行一个块。

标签: python loops enter


【解决方案1】:

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

【讨论】:

  • 这当然可以,但这不是我要寻找的答案。如果我按照建议按回车键,它将执行循环,然后下一个打印将是一个新语句。我猜的问题应该是,如何在终端上的循环之后在执行循环之前添加额外的语句?
  • @ViniciusSantana 把它放在一个方法中并运行它,我不认为 python shell 支持..
  • 你们是对的。 Python shell 每次执行只能运行一个块。
【解决方案2】:

默认的 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]: 

【讨论】:

    【解决方案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.

    【讨论】:

      猜你喜欢
      • 2014-03-09
      • 2016-08-18
      • 2014-01-22
      • 2011-08-20
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 2010-12-22
      • 2018-03-13
      相关资源
      最近更新 更多