9

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()
None
  • 3,657
  • 6
  • 41
  • 67

4 Answers4

25
  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.

kennytm
  • 491,404
  • 99
  • 1,053
  • 989
  • 1
    Is there an analogue to the trailing comma in python 3? `print('Hi')` doesn't have the same effect. – jgrant May 26 '16 at 00:53
5

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

Community
  • 1
  • 1
adw
  • 4,677
  • 24
  • 18
4

As others mention, standard out is buffered. You can try using this at points that you need the output to appear:

sys.stdout.flush()
Ned Batchelder
  • 345,440
  • 70
  • 544
  • 649
2

print automatically puts a newline at the end of a string. This isn’t necessarily what we want; for example, we might want to print several pieces of data separately and have them all appear on one line. To prevent the newline from being added, put a comma at the end of the print statement:

d=6
print d,
print d

Output:
6 6
Pramod Bhat
  • 535
  • 4
  • 7