Python Anywhere中的Python语法错误

问题描述 投票:0回答:2

我正在使用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

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

python syntax pythonanywhere
2个回答
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

点击进入,以便在>>>解决问题之前提示返回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]: 

0
投票

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

如果你有一个if语句,那么当...存在时输入的任何代码将在if语句被评估时执行。

© www.soinside.com 2019 - 2024. All rights reserved.