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:
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
>>>
Writing anything in the first column to ...
will cause this SyntaxError
, even though legal in a source file. This is because all compound statements are passed into exec(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 fact while
followed by a print
.
Hitting enter so that the prompt returns to >>>
before print
will fix the problem in interactive interpreters:
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!
>>>
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:
% 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]: