Print Single and Multiple variable in Python?

PythonServer Side ProgrammingProgramming

In this section, we are going to check printing single and multiple variable output in two different python version.

# Python 2.7

Print Single Variable

>>> #Python 2.7
>>> #Print single variable
>>> print 27
27
>>> print "Rahul"
Rahul
>>> #Print single variable, single brackets
>>> print(27)
27
>>> print("Rahul")
Rahul

Python 3.6

>>> #Python 3.6
>>> #Print single variable without brackets
>>> print 27
SyntaxError: Missing parentheses in call to 'print'
>>> print "Rahul"
SyntaxError: Missing parentheses in call to 'print'

Above syntax in 3.6, is due to: In python 3.x, print is not a statement but a function (print()). So print is changed to print().

>>> print (27)
27
>>> print("Rahul")
Rahul

Print multiple variables

Python 2.x (for e.g: python 2.7)

>>> #Python 2.7
>>> #Print multiple variables
>>> print 27, 54, 81
27 54 81
>>> #Print multiple variables inside brackets
>>> print (27, 54, 81)
(27, 54, 81)
>>> #With () brackets, above is treating it as a tuple, and hence generating the
>>> #tuple of 3 variables
>>> print ("Rahul", "Raj", "Rajesh")
('Rahul', 'Raj', 'Rajesh')
>>>

So from above output, we can see in python 2.x, passing multiple variables inside the brackets (), will treat it as tuple of multiple items

Python 3.x (for e.g: python 3.6)

#Python 3.6
#Print multiple variables
>>> print(27, 54, 81)
27 54 81
>>> print ("Rahul", "Raj", "Rajesh")
Rahul Raj Rajesh

Let’s take another example of multiple statements in python 2.x and python 3.x

raja
Published on 02-May-2019 12:29:49
Advertisements