[Tutor] Syntax error while attempting to type in multiline statements in the interactive interpreter

boB Stepp robertvstepp at gmail.com
Sat Feb 4 19:03:49 EST 2017


On Sat, Feb 4, 2017 at 5:44 PM, Alan Gauld via Tutor <tutor at python.org> wrote:
> On 04/02/17 22:56, boB Stepp wrote:
>> On Sat, Feb 4, 2017 at 4:40 PM, David <bouncingcats at gmail.com> wrote:
>>> On 5 February 2017 at 09:02, boB Stepp <robertvstepp at gmail.com> wrote:
>>>> py3: a
>>>> ['Mary', 'had', 'a', 'little', 'lamb', 'break']
>>>> py3: for w in a:
>>>> ...     print(w)
>>>> ... print('Huh?')
>>>>   File "<stdin>", line 3
>>>>     print('Huh?')
>>>>         ^
>>>> SyntaxError: invalid syntax
>>>>
>>>> I don't understand why this throws a SyntaxError.  If I wrap
>>>> essentially the same code into a function it works:
>
> Because you never completed the for loop. The interactive
> interpreter tries to exercise each Python statement as it
> goes but it cannot exercise the loop until it sees the end
> of the block. Your second print statement is outside the
> block but the block has not yet been executed so it sees
> an error.

But would it not be more consistent to assume the user knows what he
is doing based on the new (lack of) indentation being used, accept
that a new section of code outside of the for loop is being typed in,
and wait for the blank line before executing everything typed in?

>
> Alternatively if you put your code inside a function
> definition it will understand it because it interprets
> the full definition. Then when you call the function
> it executes it as a whole. There is no discrepency in
> what the interpreter is trying to interpret. But when
> you do it at the top level  the interpreter is still
> waiting for the end of the loop.

Again, the interpreter is waiting for that blank line before deciding
the function definition is complete.  Why cannot this be the key
criteria for the for loop with additional code being added, wait for
the blank line to be entered, and then execute the whole shebang?  To
me, this seems to be more consistent behavior.

> Does that help?

It confirms what I was concluding.  This is what happens when I have
some extra time on my hand, decide to carefully scrutinize the
official Python 3 tutorial, and then think, wonder and play around in
the interpreter.  ~(:>))


-- 
boB


More information about the Tutor mailing list