Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using print() (the function version) in Python2.x

I understand the difference between a statement and an expression, and I understand that Python3 turned print() into a function.

However I ran a print() statement surrounded with parenthesis on various Python2.x interpreters and it ran flawlessly, I didn't even have to import any module.

My question: Is the following code print("Hello SO!") evaluated as a statement or an expression in Python2.x?

like image 952
rahmu Avatar asked Aug 28 '12 15:08

rahmu


People also ask

How do you write the print method in Python 2 x?

Note: The print() function doesn't support the “softspace” feature of the old print statement. For example, in Python 2. x, print "A\n", "B" would write "A\nB\n" ; but in Python 3.0, print("A\n", "B") writes "A\n B\n" .

What is the difference between print in Python 2 and 3?

In Python 2, print is a statement that does not need a parenthesis. In Python 3, print is a function and the values need to be written in parenthesis.


2 Answers

Consider the following expressions:

a = ("Hello SO!") a = "Hello SO!" 

They're equivalent. In the same way, with a statement:

statement_keyword("foo") statement_keyword "foo" 

are also equivalent.

Notice that if you change your print function to:

print("Hello","SO!") 

You'll notice a difference between python 2 and python 3. With python 2, the (...,...) is interpteted as a tuple since print is a statement whereas in python 3, it's a function call with multiple arguments.

Therefore, to answer the question at hand, print is evaluated as a statement in python 2.x unless you from __future__ import print_function (introduced in python 2.6)

like image 95
mgilson Avatar answered Sep 19 '22 22:09

mgilson


print("Hello SO!") is evaluated as the statement print ("Hello SO!"), where the argument to the print statement is the expression ("Hello SO!").

This can make a difference if you are printing more than one value; for example print("Hello", "world") will print the 2-element tuple ('Hello', 'world') instead of the two strings "Hello" and "world".

For compatibility with Python 3 use from __future__ import print_function:

>>> print("Hello", "world") ('Hello', 'world') >>> from __future__ import print_function >>> print("Hello", "world") Hello world 
like image 24
ecatmur Avatar answered Sep 20 '22 22:09

ecatmur