Why does Python 3 print end “” produce an exception in the interpreter but not from import?

  • A+
Category:Languages

In Python 3, this works when importing from a file:

myInt = 0 while (myInt < 10):     print (myInt, end='')     myInt += 1 print (' are Numerals.') 

producing the expected result: "0123456789 are Numerals."

But if the code is pasted directly into an interpreter, the last line produces an exception. In fact, anything after the while block exits does:

    File "<stdin>", line 4     print (' are  Numerals.')         ^ SyntaxError: invalid syntax 

[The following is a reply to François in the form of focusing the question.]

It doesn't work in Python 2 using the trailing "," construct either...

Adding a blank line after the while block doesn't work as it clearly won't produce the desired result, namely "0123456789 are Numerals." Taking Jean-François' lead, however, this produces a similar result:

myInt = 0 res="" while (myInt < 10):     res += str (myInt)     myInt += 1  res += ' are my Numerals.' print (res) 

But is there any way of forcing the end of the while block in the interpreter which would allow printing (or string compilation, or whatever) to continue? Well, I can produce the result, when I use else and enter the following, a line at a time:

>>> myInt = 0 >>> while (myInt < 10): ...     print (myInt, end='') ...     myInt += 1 ... else: ...     print (' are Numerals.') ...  0123456789 are Numerals. 

but when I copy/paste the whole code into the interpreter, the exception is raised. So what is the difference between copy-pasting into the interpreter and typing it a line at a time? I'm even more curious now!

 


The interpreter expects input in a very specific form for multi-line statements. You can see that by inputting the lines one at a time.

>>> myInt = 0 >>> while (myInt < 10): ...  print (myInt, end='') ...  myInt += 1 ... print (' are Numerals') 

After a multi-line statement, the interpreter expects a blank line to signify the end of the block. When it encounters a new, un-indented statement immediately, it's confused.

Adding a blank line after the end of the while loop will allow the interpreter to understand your block. Remember that the Python interpreter always runs one statement at a time. When you copy-paste multiple lines, you're really running them as completely separate statements, and in the interpreter, a multi-line statement has to be terminated by a newline.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: