Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python trailing comma after print executes next instruction

Tags:

python

text

If a trailing comma is added to the end of a print statement, the next statement is executed first. Why is this? For example, this executes 10000 ** 10000 before it prints "Hi ":

print "Hi",
print 10000 ** 10000

And this takes a while before printing "Hi Hello":

def sayHello():
    for i in [0] * 100000000: pass
    print "Hello"
print "Hi",
sayHello()
like image 607
None Avatar asked Oct 24 '10 18:10

None


2 Answers

  1. In Python 2.x, a trailing , in a print statement prevents a new line to be emitted.

    • In Python 3.x, use print("Hi", end="") to achieve the same effect.
  2. The standard output is line-buffered. So the "Hi" won't be printed before a new line is emitted.

like image 98
kennytm Avatar answered Oct 18 '22 04:10

kennytm


You're seeing the effects of stdout buffering: Disable output buffering

like image 27
adw Avatar answered Oct 18 '22 06:10

adw