The function which prints the specified message on the screen and any other output device is the Python Print() function. By the end of this article, we expect you to be comfortable with what print() is and how it works, and we also show some amazing things one can do using python print().
The Python print() function helps in printing the specified message onto the screen, or any other standard output device.
The message can be a string, or any other object, the object will be converted into a string before being written to the screen. Whatever be the message format i.e string or any other object, it finally gets converted into a string only.
The print function in Python is a function which is used to output to the console window whatever you say you want to print out. At the first instance, it might seem that the print function is rather pointless for programming, but it is actually one of the most widely used functions in all of python.
The reason for this being that print() function is great as a debugging tool. "Debugging" can be defined as the act of finding and removing or fixing errors and mistakes present in the code which allows the program to operate according to a set of specifications.
Whenever something isn't acting as expected, one can use the print function to print out what is happening in the program. A lot of times, you would be expecting a variable to be a certain way, but the problem is that you cannot see what the program sees. When you print out the variable, you might be able to see what the variable actually is.
Before we proceed let us look at the python print() format.
The syntax of the print function is of the following format
print(object(s), separator=separator, end=end, file=file, flush=flush)
A point to remember is that sep, end, file, and flush are all keyword or named arguments. In case you would want to use sep argument, you have to write:
print(*objects, sep = 'separator') not print(*objects, 'separator')
One important thing to remember is that Python print() returns no value. It returns None. This is because in Python 2.x, it is considered as a reserved keyword and not a function.
Let us now move forward by going through a couple of examples using the Python print(). We shall also cover examples using
But before that let us see the basic functioning using python print() examples.
Let us carefully understand how print in python actually works.
print("Python is fun.") a = 5 # Two objects are passed print("a =", a) b = a # Three objects are passed print('a =', a, '= b')<br /><br />
When you run the program, the output generated will be:
Python is fun.
a = 5
a = 5 = b
In the previous program, only the objects parameter has been passed to print() function (in all three print statements).
' ' separator is used. Observe the space between two objects in output.
end parameter 'n' (newline character) is used. Observe that each print statement displays the output in the new line.
file is sys.stdout. The output has been printed on the screen.
flush is False. This means that the stream is not forcibly flushed.
Now let us look at another example of Python print() with separator and end parameters which we will further elaborate later in this article.
a = 5 print("a =", a, sep='00000', end='nnn') print("a =", a, sep='0', end='')
When you run the program, the output generated will be:
We have passed the sep and end parameters in the above program.
Finally, let us see how Python print() works with the file parameter
In Python, you can print the objects to a file by specifying the file parameter.
sourceFile = open('python.txt', 'w') print('Pretty cool, huh!', file = sourceFile) sourceFile.close()
What this program does is that it tries to open the python.txt in writing mode. If this file doesn't exist, python.txt file is created at that moment and then opened in writing mode. Here, we have passed file object 'sourceFile' as the file parameter. Here, 'Pretty cool, huh!' is the string object which is printed to python.txt file.
Finally, the close() method helps in closing the file.
Usually, the separator between the arguments in the print() function in Python is space by default (softspace feature) , which can be changed and be made to any character, integer or string as per our requirements. To achieve the same, we use the ‘sep’ parameter, which is found only in python 3.x or later. It also finds its use in formatting the output strings.
Let us take a look at the below examples:
#code for disabling the softspace feature print('G','F','G', sep='') #for formatting a date print('09','12','2016', sep='-') #another example print('pratik','geeksforgeeks', sep='@') <br /><br />
The output generated will be of the following format:
When the sep parameter is coupled with end parameter it produces amazing results. Some examples showing the combination of the two are:
print('G','F', sep='', end='') print('G') #n provides new line after printing the year print('09','12', sep='-', end='-2016n') print('prtk','agarwal', sep='', end='@') print('geeksforgeeks')
The output generated is a below:
Now let's continue with doing more typing of variables and printing them out. This time we'll use the concept of “format string." Whenever you put " (double-quotes) around a piece of text, it results in the formation of a string. We can do a lot with strings. We can print strings, we can save strings to files, we can also send strings to web servers, and many other things.
Strings are very handy, and in this exercise, we will teach you how to make strings that have variables embedded in them. With the help of specialized format sequences we can embed variables inside a string. And by putting these variables at the end of this sequence with a special syntax that communicates to Python that it is a format string and the variables need to be put here.
Though it's difficult to completely understand at this point of time, just type this in. You'll get clarity once you see the output.
my_name = 'Zed A. Shaw' my_age = 35 # not a lie my_height = 74 # inches my_weight = 180 # lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown' <br /> print "Let's talk about %s." % my_name print "He's %d inches tall." % my_height print "He's %d pounds heavy." % my_weight print "Actually that's not too heavy." print "He's got %s eyes and %s hair." % (my_eyes, my_hair) print "His teeth are usually %s depending on the coffee." % my_teeth <br /> # this line is tricky, try to get it exactly right print "If I add %d, %d, and %d I get %d." % ( my_age, my_height, my_weight, my_age + my_height + my_weight)
A point to remember is to put # -*- coding: utf-8 -*- at the top in case you notice non-ASCII characters and face an encoding.
This is the expected output:
$ python ex5.py
Let's talk about Zed A. Shaw.
He's 74 inches tall. He's 180 pounds heavy. Actually that's not too heavy. He's got Blue eyes and Brown hair. His teeth are usually White depending on the coffee. If I add 35, 74, and 180 I get 289.<br /><br />
We would like to challenge you with a couple of exercises. Try them out yourself.
Whenever people switch from C/C++ to Python, they wonder how to print two or more variables or statements without progressing onto a new line in python, since, by default, the python print() function ends with newline. Python provides you with a predefined format wherein if you use print(a_variable) then it will go to the next line automatically.
Let us look at the following example:
will generate this
But in case you would like to print on the same line, what can we do?
Input : print("geeks") print("geeksforgeeks")
Output : geeks geeksforgeeks
Input : a = [1, 2, 3, 4]
Output : 1 2 3 4
One thing to be noted is that the solution which has been discussed is totally dependent on the python version being used.
Print without newline in Python 2.x
# Python 2 code for printing # on the same line printing # geeks and geeksforgeeks # in the same line print("geeks"), print("geeksforgeeks") # array a = [1, 2, 3, 4] # printing a element in same # line for i in range(4): print(a[i]), <br /><br />
geeks geeksforgeeks 1 2 3 4
Print without newline in Python 3.x
# Python 3 code for printing # on the same line printing # geeks and geeksforgeeks # in the same line print("geeks", end =" ") print("geeksforgeeks") # array a = [1, 2, 3, 4] # printing a element in same # line for i in range(4): print(a[i], end =" ") Copy CodeRun on IDE<br /><br />
1 2 3 4
With the Python 3.0 version, the python print() statement has changed from being a statement to a function. With more flexibility at its disposal python print() can help you do amazing things. We hope this article has given you the base on which you can master!!
Free Demo for Corporate & Online Trainings.