In Python 2.7 both the following will do the same
print("Hello, World!") # Prints "Hello, World!"
print "Hello, World!" # Prints "Hello, World!"
However the following will not
print("Hello,", "World!") # Prints the tuple: ("Hello,", "World!")
print "Hello,", "World!" # Prints the words "Hello, World!"
In Python 3.x parenthesis on print is mandatory, essentially making it a function, but in 2.7 both will work with differing results. What else should I know about print in Python 2.7?
See also: Getting SyntaxError for print with keyword argument end=' ' for another consequence in Python 2.x of the difference in print handling.
In Python 2.x
printis actually a special statement and not a function*.This is also why it can’t be used like:
lambda x: print xNote that
(expr)does not create a Tuple (it results inexpr), but,does. This likely results in the confusion betweenprint (x)andprint (x, y)in Python 2.7However, since
printis a special syntax statement/grammar construct in Python 2.x then, without the parenthesis, it treats the,‘s in a special manner – and does not create a Tuple. This special treatment of theprintstatement enables it to act differently if there is a trailing,or not.Happy coding.
*This
printbehavior in Python 2 can be changed to that of Python 3: