Python Print() Function

A lot of us, while reading this tutorial, might think that there is nothing undiscovered about a simple Python Print function since we all would have started learning Python with the evergreen example of printing Hello, World!. It's also true that Python or, for that matter, any programming language, the Print function is the most basic & the baby step that we take while learning a particular language. However, while learning a programming language, we sometimes tend to focus on more advanced topics & many times forget the intricacies or capabilities of a simple function that we might almost always use.

This focus of this will be entirely on Python’s Print function, which we will soon learn to see is actually the most underestimated function.

Let’s begin by printing the Hello, World! example.

Unlike Python2, which did not require us to put a parenthesis, in Python3, parenthesis is a must else it will raise a syntax error as shown below.

From the above output, we can conclude that in Python3, print() is not a statement but a function.

Having said that, let’s check the type/class of the print() function.

It returns builtin_function_or_method, which means it is a predefined or a built in Python Function.

Now let’s say we want to add a new line or a vertical space between the below two outputs, to achieve this we can simply call the print() function without passing any argument in it.

Let’s look at the syntax of the print() function. print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) As we know by now, the print function Prints the values to a stream, or to sys.stdout by default. The sys.stdout or system standard output means the print function will print the output on the screen, & it can even be changed to stdin or stderr.

sep: It can be a string which we would like to insert between values, defaults to space.

Let’s put a list of words inside the print function & separate them with a new line. Remember, by default; the separator adds a blank space between each word.

Similarly, we can separate them with a comma, or add two \n which will add an empty line in between or even add a plus (+) sign.

Before we jump on to the next argument, i.e., end, remember that we can also pass in a variable to the print function. To understand this, let's take an example by defining a list of integers & pass it to the print function. We would expect it to print the list of integers.

end: It is a string appended after the last value, defaults to a newline. It allows the programmer to define a custom ending character for each print call other than the default newline or \n.

Let’s say we have two strings & we want to join them together with space, all we would need to do is in the print function of the first string str1 add end argument with quotes, & we can expect the two strings to be joined by a space.

Let’s take another example where we have a function whose job is to print all values within a list on the same line. We could achieve this with the end argument, as shown below:

file: A file-like object (stream); defaults to the current sys.stdout. Here, we can mention the file in which we would like to write or append the output of the print function.

By using the file argument, we can store the output of the print function to a file in various formats like .csv, .txt, etc. Let's understand this by taking an example where we iterate over each element of the list. It is saved in a text file. To accomplish this, first, we will open a text file in an append state in which we will be saving the output of the print statement. Next, we will define the function whose output will be appended in the text file.

Once the above function execution completes, we should see a file named print.txt in our current directory. Let's open it & see its contents.

From the above output, it is clear that we can even save the output to files & not just print the output on the terminal or within the notebook.

flush: It determines whether to forcibly flush the stream. By default, it is set to False.

Typically, output to a file or the console is buffered, with text output at least until we print a newline. Buffer means that the output is stored in some kind of a register where the output resides before it is ready to be stored or the file is finally closed. The job of the flush is to make sure that the output, which is being buffered, goes to the destination safely.

If we run the above lines of code in the terminal, we will notice that the prompt string does not show up until the sleep timer ends & the program exits. However, if we add flush=Truein the print function, we will see the prompt, & then we will have to wait for 5 seconds for the program to finish.

Somehow the Jupyter Notebook or Jupyter Lab takes care of it & shows the prompt before the 5 seconds timer, so if we want to test this functionality of print, make sure to run it in command line terminal & not on the jupyter notebook.

Let’s now see how we can make use of the print function to take input from the user in the jupyter notebook. For this, we will use python’s builtin function input().

As soon as we run the above cell, we should see an output as shown below:

Here we defined an optional named argument end that we learned before, which concatenates the static statement inside print statement with the user input.

Let’s see some cooler ways of printing variable values inside the print function.

  • To display a variable’s value along with a predefined string, all we need to do is add a comma in between the two. Here the position of the predefined string & the variable does not matter.

We can make use of the format argument where we can pass as many variables as we want to print. When we pass the variables in the format function, we need to specify the index numbers (order in which they are placed inside the format argument) in the predefined string. So this print function will now act as a template for us.

Another thing to remember is that here the index numbers are represented with a curly bracket {} representing a placeholder.

Let’s understand it with the below example:

If we put the index number of the second variable at both places, as expected, it will print the same values, in this case, b variable for both.

Similar to a format argument where our print function acts as a template, we have a percentage (%) sign that we can use to print the values of the variables.

Like format argument, this also has a concept of placeholders. However, unlike the formatfunction where we pass in just the index numbers, in this, we also need to specify the datatype the placeholder should expect.

  • %d is used as a placeholder for numeric or decimal values
  • %s is used as a placeholder for strings

Let’s see what happens if we specify %s for the variable a which is an integer.

As we can see from the above example, it still works. The reason is that the Print function implicitly performed typecasting & converted the integer to a string. However, the opposite is not true. It will fail to convert a string to an integer & will result in a TypeError.

Let’s Find Out

Conclusion

This tutorial was a good starting point for beginners who aspire to become proficient in Python. You might want to play around with the Print function a bit more & explore a few more functionalities of it that might have been missed out in this tutorial.

RELATED LINKS:

Data Scientist & Machine Learning Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store