Reputation: 685
What is the difference between prints in python:
print 'smth'
print('smth')
Upvotes: 3
Views: 1481
Reputation: 1659
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.
Upvotes: 0
Reputation: 104102
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.
Upvotes: 4
Reputation: 34047
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
Upvotes: 7