Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the meaning of "the interpreter inserts a newline before it prints the next prompt if the last line was not completed."

Tags:

python

I learn Python by reading The Python Tutorial of python.org. When I read the third chapter:3. An Informal Introduction to Python, I can't understand the last sentence of the article which is "the interpreter inserts a newline before it prints the next prompt if the last line was not completed." Does somebody know what it is meaning? It is better if there is an example. Thanks.

like image 877
Leeway Avatar asked Jan 27 '26 12:01

Leeway


1 Answers

Each time you use a print statement that ends in a comma, the interpreter sets a flag to remember that it didn't write a newline yet.

Because putting the next prompt on the same line as those numbers would be inconvenient (it won't be in the left-most column as you expect it to be), Python will write a newline character so that the prompt ends up in the left column again; it uses that flag set by the print statement to detect this situation.

So instead of getting this in your interactive session:

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> 

you see this:

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> 

Interestingly enough, in Python 3 no such flag is set anymore because print() is now a function. As a result, the interactive interpreter can no longer detect this situation and puts the prompt right after the numbers:

>>> import sys
>>> sys.version
'3.4.2 (default, Feb 10 2015, 10:25:29) \n[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)]'
>>> a, b = 0, 1
>>> while b < 1000:
...     print(b, end=',')
...     a, b = b, a+b
... 
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,>>> 
like image 130
Martijn Pieters Avatar answered Jan 30 '26 01:01

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!