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

boB Stepp robertvstepp at gmail.com
Sat Feb 4 17:56:51 EST 2017


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:
>
> From [1]: "When a compound statement is entered interactively, it must
> be followed by a blank line to indicate completion (since the parser
> cannot guess when you have typed the last line). Note that each line
> within a basic block must be indented by the same amount."
>
> Does that help?

Not really.  I do not understand why I can define a function in the
interactive interpreter and nest (apparently) any number of for loops,
if-elif-else constructs, etc., and as long as I get the indentation of
each block correct, it will accept it.  But apparently if I start off
with something which is by definition multiline like typing in a for
loop, I cannot continue the multiline statements with something
outside the for loop even if the indentation indicates that the
following statement is not part of the for loop above.  I can accept
this, but I do not understand why this can't be parsed correctly by
the interpreter solely based on the indentation and lack of
indentation being used.

C'est la vie Python!



-- 
boB


More information about the Tutor mailing list