Back to articles list Articles
8 minutes read

How to Print in Python - A Detailed Guide for Beginners

How often have you used the Python print() function? Let’s take a deep-dive look at this built-in function. Since you’ll be using it often in your programs, we’ll walk you through all its functionality.

Python has many useful built-in functions that you can start using straight out of the box. You can check out all of them in the official Python documentation. One of the most useful is the print() function, which you can use to print a message to the screen or to a file. This function is quite versatile and can probably do more than you realize. In this article, we’ll take a detailed look at everything this function can do. It’s worth getting familiar with it, since you’ll be using this function all the time.

This article is aimed at beginners. We’ll start from the basics and work up to more advanced usage of the Python print() function. If you need some material to learn the fundamentals of Python, consider our Python Basics: Part 1 course, which includes 95 interactive exercises to get you on your feet. For a more in-depth introduction to programming, the Python Basics track and the Learn Programming with Python track bundle together several beginner friendly courses.

Using Python print() with Hello, World!

There’s a good chance the ‘Hello, World!’ program was your first exposure to programming. This is used to illustrate a language’s basic syntax. In some languages (such as C++), this simple program requires you to import a library, define a function, and execute a print command. In Python, however, it’s a simple one liner that shows the basic usage of the print() function. Just open a Python console and execute the following command:

>>> print('Hello, World!')
Hello, World!

This is about as simple as it gets. Nevertheless, there are a few interesting things to note about this program. First, it’s a nice example of how simple and intuitive Python syntax can be. This makes learning Python easier than many other programming languages, as we discuss in How Long Does It Take To Learn Python?.

Second, the print() statement only has one required argument, which is represented by the *objects parameter in the documentation. It’s a string in the example above, but it can be many different things.

As a side note, you can write your strings with either single quotes ('text') or double quotes ("text"). If you want to define a string containing a single-quote character, you’ll need double quotes ("who's there?"). Otherwise, the choice is up to you. You can learn more about strings in the Working with Strings in Python course.

print(anything)

The print() statement can be used to print just about anything. To demonstrate this, let’s define a variable and print it:

>>> anything = 3
>>> print(anything)
3

In this example, we defined the variable anything to be an integer. Now let’s try defining it as a data structure, such as a list:

>>> anything = [1, 2, 3]
>>> print(anything)
[1, 2, 3]

You can also define multiple objects separated by a comma, and each of which may have a different type. You can print a string along with the list we defined above:

>>> print('List:', anything)
List: [1, 2, 3]

To unpack the list and display the data nicely, you can use a starred expression:

>>> print('List:', *anything)
List: 1, 2, 3

Try playing around with a few different data types as the anything variable. For example, try defining a float, or a dictionary, or even a complex number.

All objects to be printed are converted to strings behind the scenes, which allows us to do this mixing of data types. For the final example, we’ll define a function to return an integer, then print the result in a string. Our simple function will simply add two integers:

>>> def add(a, b):
...     return a + b

Our function doesn’t define the allowed input data types. For example, you could use strings or lists, but we’ll just use integers. That means the result of the add() function is also an integer, but we can easily print it in a string:

>>> result = add(1, 2)
>>> print('The result is {}'.format(result))
The result is 3

A final note for this section: the print() function itself returns None. This means you can’t save the print() statement as a variable. It’s good to keep this in mind if you’re trying to debug your code with a print() statement. For example:

>>> print_me = print('Super important error message')
>>> print(print_me)
None

Optional Arguments

The Python print() function has four optional arguments that allow you to really customize how the function behaves. The first one we’ll look at is sep, which defines the separator to use if more than one object is provided as the first argument. Its default value is a space, and the value must be a string. Building on an example from the previous section, we can do the following:

>>> anything = [1, 2, 3]
>>> print('List:', anything, sep='\n')
List:
[1, 2, 3]

Here, we have defined the newline character ('\n'), which prints the two objects on different lines, as the separator. You can use this argument to format the style of the output from the print() statement. Try defining a tab ('\t') as the separator and see what you get.

Next, we have the end argument. This allows you to define something to be printed at the end of the line; the default value is the newline character. Once again, this value is only allowed to be a string, but you can make the string do several things. For example:

>>> print('List:', anything, sep='\t', end='!\n\n')
List:   [1, 2, 3]!

We changed the separator to a tab and added an exclamation point and two new line characters at the end of the output. If you run this in your Python console, you’ll notice extra space printed below the output. This can once again be used to format the style of the objects printed.

The third optional argument in the Python print function is file. The default value is None, which prints the objects to the screen. This is done via sys.stdout, which is a file object corresponding to the standard output stream. You can provide a different file object to define somewhere else to write the output. For example:

>>> with open('data.csv', 'w') as open_file:
... 	print('Name', 'Age', 'Occupation', sep=',', file=open_file)
...	print('Jon Anderson', 53, 'Pilot', sep=',', file=open_file)

This prints two lines to the open_file object. Each line contains 3 objects to be printed, each of which is separated by a comma. We have thus created a CSV file and saved it as data.csv.

Before we move on to the final argument, there’s a second use case for the file argument worth discussing. We mentioned the standard output stream. This is one of three standard streams that control how the program interacts with its environment. Another standard stream is standard error, or stderr. This can print a message to the screen or to a file; importantly, it is independent of the standard output stream. This means you can more reliably log errors before your program crashes. To take advantage of this when debugging your programs, you can do the following:

>>> import sys
>>> print('A Custom Error Message', file=sys.stderr)
A Custom Error Message

Here, we used the file argument to redirect the error message to the standard error stream. This still results in the error message being printed to the screen, but it’s a more reliable way to debug your programs, since it is independent of other things being printed via the standard output stream.

The final argument is flush, which has the default value false. Normally, the output from the print statement is buffered. The buffer is only flushed when it’s full or when a newline character is reached. Setting flush=True forces the buffer to be flushed before this happens. To demonstrate this, create the following program and save it as flush_output.py:

import time
for i in range(5, 0, -1):
    print(i, end=' ', flush=False)
    time.sleep(1)
print('\nFinished')

After running the program from the console, it waits 5 seconds then prints the numbers 5 to 1 on the same line, followed by the word 'Finished' on a new line. Try setting flush=True and see what you get. It should resemble a countdown clock, where the numbers are printed one after the other with a one second pause between them, once again followed by 'Finished' on a new line. Remember,  the default value for the end argument is the newline character, which would flush the buffer by default. Therefore, after setting end to something else and flush=True, we get the countdown clock.

Now You Know the Python print() Statement

There’s more to the Python print() statement than meets the eye. Now you should have the necessary tools to take advantage of this very common function.

Whether printing output to the screen, errors to an error log, or taking user input, the print() function in Python is very versatile. For more hands-on material to accelerate your learning, consider taking the Python Practice: Word Games course. Taking interactive courses is a great way to learn Python, as we discuss in Different Ways to Practice Python and The 5 Best Resources to Start Learning Python. With a little time and effort, you’ll become a Python master!