3

What is the difference between prints in python:

print 'smth'
print('smth')
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
Edd
  • 665
  • 1
  • 5
  • 13
  • No real difference, the first is sort of a syntactical sugar. – gravetii Feb 05 '14 at 15:23
  • 3
    @gravetii: no, the second only works coincidentally, most of the time, in Python 2, where `print` is a statement, not a function. The first isn't syntactic sugar at all, it's the correct usage. – Wooble Feb 05 '14 at 15:27

3 Answers3

7

print is made a function in python 3 (whereas before it was a statement), so your first line is python2 style, the latter is python3 style.

to be specific, in python2, printing with () intends to print a tuple:

In [1414]: print 'hello', 'kitty'
hello kitty

In [1415]: print ('hello', 'kitty')
('hello', 'kitty')

In [1416]: print ('hello') #equals: print 'hello', 
                           #since "()" doesn't make a tuple, the commas "," do
hello

in python3, print without () gives a SyntaxError:

In [1]: print ('hello', 'kitty')
hello kitty

In [2]: print 'hello', 'kitty'
  File "<ipython-input-2-d771e9da61eb>", line 1
    print 'hello', 'kitty'
                ^
SyntaxError: invalid syntax
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
4

In python 3, print is a function.

>>> print('a','b','c')
a b c

In Python 2, print is a keyword with more limited functionality:

>>> print 'a','b','c' 
a b c

While print() works in Python 2, it is not doing what you may think. It is printing a tuple if there is more than one element:

>>> print('a','b','c')
('a', 'b', 'c')

For the limited case of a one element parenthesis expression, the parenthesis are removed:

>>> print((((('hello')))))
hello

But this is just the action of the Python expression parser, not the action of print:

>>> ((((('hello')))))
'hello'

If it is a tuple, a tuple is printed:

>>> print((((('hello',)))))
('hello',)

You can get the Python 3 print function in Python 2 by importing it:

>>> print('a','b','c')
('a', 'b', 'c')
>>> from __future__ import print_function
>>> print('a','b','c')
a b c

PEP 3105 discusses the change.

dawg
  • 98,345
  • 23
  • 131
  • 206
0

You can use parenthesis in Python 2 and 3 print, but they are a must in Python 3.

Python 2:

print "Hello"

or:

print("Hello")

Whereas in Python 3:

print "Hello"

Gets you this:

  File "<stdin>", line 1
    print "Hello"
                ^
SyntaxError: Missing parentheses in call to 'print'

So you need to do:

print("Hello")  

The thing is, in Python 2, print is a statement, but in Python 3, it's a function.

Trooper Z
  • 1,617
  • 14
  • 31