I'm using Python with DataCamp and Python Anywhere, and they seem to disagree on what a syntax error is. I've recently just started, so I tried this line of code:
n = 5
while n > 0:
print (n)
n = n - 1
print ('Blastoff!')
It runs like it's supposed on DataCamp, but with Python Anywhere, I get the following error:
File "<stdin>", line 5
print ("Blastoff!")
^
SyntaxError: invalid syntax
I don't know what it's referencing or trying to tell me. The error message is unhelpful, and I don't know why I'm getting two different evaluations here.
When pasting into interactive interpreter, you must have an empty line after a block statement, before the next statement. Here's the output from the Python Anywhere interpreter embedded on http://www.python.org:
Writing anything in the first column to
...
will cause thisSyntaxError
, even though legal in a source file. This is because all compound statements are passed intoexec(compile(... 'single'))
when completed; and the python REPL is being a bit stupid here, thinking that it was just one statement, when it is in factwhile
followed by aprint
.Hitting enter so that the prompt returns to
>>>
beforeprint
will fix the problem in interactive interpreters:But notice that the
while
loop now runs as soon as the compound statement is terminated, i.e. before the>>>
prompt shows again.There are other shells besides the standard Python REPL. One popular, ipython, has a console shell that will recognize copy-pasted content and run this one correctly: