Python Anywhere中的Python语法错误

时间:2017-09-02 17:21:39

标签: python syntax pythonanywhere

我正在使用Python与DataCamp和Python Anywhere,他们似乎不同意语法错误是什么。我刚刚开始,所以我尝试了这行代码:

n = 5
while n > 0:
   print (n)
   n = n - 1
print ('Blastoff!')

它的运行方式与在DataCamp上的运行方式相同,但在Python Anywhere中,我收到以下错误:

  File "<stdin>", line 5
    print ("Blastoff!")
        ^
SyntaxError: invalid syntax

我不知道它在引用或试图告诉我什么。错误消息没有用,我不知道为什么我在这里得到两个不同的评估。

2 个答案:

答案 0 :(得分:2)

粘贴进入交互式解释器时,在下一个语句之前的块语句之后必须有空行。这是嵌入在http://www.python.org上的Python Anywhere解释器的输出:

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]: 

答案 1 :(得分:0)

PythonAnywhere和shell都会将...中的任何内容视为第一个语句的一部分,这意味着在ifwithwhile或{{{{}}之后的任何内容当评估第一个语句时,应该执行以3个点开头的1}}。

如果您有一个for语句,那么在if时输入的任何代码都将在if语句被评估时执行。