当将粘贴到interactive interpreter时,您必须在块语句之后,在下一条语句之前有一个空行。 下面是嵌入在上的Python Anywhere解释器的输出http://www.python.org:
Python 3.6.0 (default, Jan 13 2017, 00:00:00)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> n = 5
>>> while n > 0:
... print (n)
... n = n - 1
... print ('Blastoff!')
File "<stdin>", line 4
print ('Blastoff!')
^
SyntaxError: invalid syntax
>>>
将第一列中的任何内容写入...
将导致此SyntaxError
,即使在源文件中合法。 这是因为所有复合语句都传入exec(compile(... 'single'))
完成后;python REPL在这里有点愚蠢,认为它只是一个语句,当它实际上是while
后跟一个print
时。
按enter键使提示符返回到>>>
之前的print
将解决交互式解释器中的问题:
Python 3.6.0 (default, Jan 13 2017, 00:00:00)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> n = 5
>>> while n > 0:
... print (n)
... n = n - 1
...
5
4
3
2
1
>>> print ('Blastoff!')
Blastoff!
>>>
但是请注意,while
循环现在在复合语句终止后立即运行,即在>>>
提示符再次显示之前。
除了标准的Python REPL之外,还有其他shell。 一个流行的ipython有一个控制台shell,它可以识别复制粘贴的内容并正确运行此内容:
% ipython
Python 3.5.3 (default, Jan 19 2017, 14:11:04)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: n = 5
...: while n > 0:
...: print (n)
...: n = n - 1
...: print ('Blastoff!')
...:
5
4
3
2
1
Blastoff!
In [2]:
PythonAnywhere和shell都将
...
中的任何内容视为第一条语句的一部分,这意味着在计算第一条语句时,应该执行以3个点开头的aif
或with
或while
或for
之后的任何内容。如果你有一个
if
语句,在...
时输入的任何代码将在计算if语句时执行。