[Tutor] Help with simple text book example that doesn't work!!!

Hugo Arts hugo.yoshi at gmail.com
Sun Apr 4 16:05:10 CEST 2010

On Sun, Apr 4, 2010 at 3:15 PM, Brian Drwecki <drwecki at gmail.com> wrote:
> As for the exact error code....here it is.
> while True:
>     reply = raw_input('Enter text:')
>     if reply == 'stop':
>         break
>     elif not reply.isdigit(  ):
>         print 'Bad!' * 8
>     else:
>         print int(reply) ** 2
> print 'bye'
> SyntaxError: invalid syntax  (note it highlights the print code)...
> This works!!!
>>>> print'bye'
> bye

the interactive interpreter is a comparatively simple machine.
Notably, it expects you to type only a single statement at a time. It
may be a compound statement or a simple statement, but it must be only
one statement. Your code, at the top level consists of two statements,
a 'while' statement (which is compound) and a print statement. The
interpreter expects only a single statement, and complains when it
finds the second one:

In [2]: if True:
   ...:     print "inside statement one"
   ...: print "inside statement two"
   File "<ipython console>", line 3
     print "inside statement two"
SyntaxError: invalid syntax

In [3]:

If you embed these two statements inside a single compound statement
(whether that is a loop, conditional, function, whatever) the
interpreter will stop complaining again, since the top-level statement
again consists of only a single statement:

In [8]: if True:
   ...:     if True:
   ...:         print "sub-statement one"
   ...:     print "sub-statement two"
sub-statement one
sub-statement two
In [9]:

Note that when interpreting a python script, there is no such
limitation, and multiple top-level statements are perfectly fine.

I haven't read the source, but my guess is that when parsing python
source code, the parser uses a StatementList AST node as the root to
parse a list of statements, while the interactive interpreter doesn't
create this AST node. That's why it's limited to a single statement at
a time.


More information about the Tutor mailing list