Progress

Python print() function for Output: Arguments and Examples

Python print() function for Output: Arguments and Examples

The print function in Python is mysterious for new programmers who are coming from other languages like C and C++. It support printing of different objects rather than just strings, this makes it very useful.

It has a wide range of customisations which are very helpful in different situations.

Description and Uses

The print function in Python displays any output to the terminal.

There are very different uses of the print statement. It is used to display any output message to the terminal to guide the user to interact with the program.

The print statement also serves the purpose to debug the program for errors by printing and checking the control flow of the program.

Syntax of the print function

Here is the complete syntax of the print function in Python with all accepted arguments and their default values.

Copy
print(object(s), sep=" ", end="\n", file=sys.stdout, flush= False )

Except for object(s), all other arguments must be given as keyword arguments.

Each argument in the print function is helpful in dealing with certain problems. The explanation of each parameter is in the next section.

Parameter values of the print function

The print function in Python by default accepts 5 parameters. Here is the complete explanation of them.

Object(s) Parameter

Python support printing of objects and not limited to strings. We can easily print list, dictionary, set, tuple and all other objects.

It is possible to print multiple objects in one print statement, by default they will be separated by space.

Copy
odd_List = [1, 3, 5, 7]
even_Tuple = (2, 4, 6, 8, 10)
print(odd_List, even_Tuple)
Output
[1, 3, 5, 7] (2, 4, 6, 8, 10)

Here is an example to print a dictionary in Python.

Copy
lang_dict = {1: 'C', 2: 'C++', 3: 'Python', 4: 'Java'}
print(lang_dict)
Output
{1: 'C', 2: 'C++', 3: 'Python', 4: 'Java'}

The sep Parameter

It stands for the separator. The default argument of sep is ” ” (single space).

The sep parameter defines how the objects will be separated in the output. In the above example, we see that the list and tuple output have space between them.

We can pass any string to use as a separator. Here is an example that demonstrates the use of sep parameter.

Copy
day = 3
month = 8
year = 1998
print(day, month, year, sep="-")
Output
3-8-1998

The end Parameter

As the name suggests, it denotes the end of the line of any output. The default argument of end parameter is “\n” which is the newline character.

The general use of end parameter is to combine the output of multiple print function into a single line. Here is the example that demonstrates the same.

Copy
odd_list = [1, 3, 5, 7]
for i in odd_list:
    print(i**2, end=" ") #Calculate square and print in one line
Output
1 9 25 49 

The file Parameter

The file parameter in the print function in Python defines where to display the output. The default argument of the file parameter is sys.stdout.

We can also display the output of the print function in some external file. Here is an example that does the same.

Copy
sample_file = open('sample.txt', 'w')
print("HolyCoders is blog for Programmers", file=sample_file)
sample_file.close() #Important

Note that the file argument must have write(string) method in it. If the write method is not there then it will throw an AttributeError.

It does not support binary mode files, you can use file.write() instead for such operations.

The flush Parameter

The computer buffer (memory to store temporary data) stores the output data until it is full or some other event occurs (it gets new line as input, we close the file).

The flush parameter force it to write the stored data at the desired location (file or terminal).

The default value of the flush parameter is False, which means the buffer will store data until it finds new line character (\n).

Honestly, I was unaware of this beautiful parameter for a very long time but It is very helpful in dealing with files.

Take the above example file parameter and remove the last line to close the file.

Did you see what happens?

There is no output because the input data is still in the buffer waiting for any event that triggers it to write the output. Here is the use of the flush parameter in this case.

Copy
sample_file = open('sample.txt', 'w')
print("HolyCoders is blog for Programmers", file=sample_file, flush=True) #Flush forced to write output now

Print function Return Type

The print() function return None.

How does the print function work behind the scenes?

It is very interesting to know the internal implementation of the print function in Python.

The print function first looks for __str__ method and then __repr__ method inside the object to get the data to print.

Copy
class Book:
    def __init__(self, name, pages):
        self.name = name
        self.pages = pages
    def __repr__(self):
        return "Book: {0}, Pages: {1}".format(self.name, self.pages)
    def __str__(self):
        return "The Book {0} has {1} pages".format(self.name, self.pages)

book1 = Book("Rich Dad Poor Dad", 207)
print(book1)
Output
The Book Rich Dad Poor Dad has 207 pages

Here is another example to demonstrate the use of __repr__ method.

Copy
class Book:
    def __init__(self, name, pages):
        self.name = name
        self.pages = pages
    def __repr__(self):
        return "Book: {0}, Pages: {1}".format(self.name, self.pages)

book1 = Book("Rich Dad Poor Dad", 207)
print(book1)
Output
Book: Rich Dad Poor Dad, Pages: 207

Here is an explanation of the difference between __str__ and __repr__ method.

Real-Life Examples

The print function has use cases in almost all python program to display output and debug the program.

Here is an example to open a file and print its output to the terminal.

Copy
sample_file = open('sample.txt', 'r') #Open file in read mode
contents = sample_file.readlines()  #Read and store each line of file in a list
for line in contents:
    print(line)
Output
HolyCoders is blog for Programmers

Some More Printing Examples:

Conclusion

Now you have a complete understanding of working with print function in Python. You can go out and start coding.

To avoid bugs you must use flush parameter carefully.

Share the Post ;)

Related Posts