Diving deeper into Python print

Learn to print relevant messages to various outputs using Python. Examples for both Python 2 and Python 3 are provided.

Diving deeper into Python print
Printing in Python

I write this blog with an intention of providing a deeper context and importance to print that it rarely gets.

Pretty much every programmer learns to code by printing Hello World. However, rarely any blog or video on the internet takes a deep dive into the mysteries of print in Python.

In order to help the Python 2 programmers in transitioning to Python 3, I will provide examples for both versions of Python 2 and 3. That way you are aware of the history of print() and how it has changed in Python 3.

If you are a Python 2 programmer, I highly recommend you moving to Python 3. Check out my article on Benfits of Python 3 over Python 2.

Table of Content

  1. Python is dynamically typed
  2. Writing a Hello World program
  3. General Syntax of Print
  4. Printing multiple elements
  5. Printing to a newline
  6. Printing to a file
  7. Flushing
  8. Python Print Examples
  9. Problems to solve

Python is dynamically typed

Typing refers to type-checking in programming languages. There are 2 types of type-checking.

  1. Statically Typed - Data type is checked during compilation
  2. Dynamically Typed - Data type is checked during execution

Python is an interpreted language. It executes each statement line by line and thus type-checking happens on the fly, during execution.

Hence, Python is a Dynamically Typed Language.

Writing a Hello World program

Let’s begin with a Hello World program.

#Python 2
print 'Hello World'
>>> Hello World

# Python 3
print('Hello World')
>>> Hello World

YES. It is that easy.

You can notice that you need to pass in your messages inside a bracket in Python 3 compared to Python 2. It’s because print is a function in Python 3. It was a statement in Python 2.

A statement in Python is a line of code that provides instruction or commands for Python to perform. A statement never returns any value.

Functions on the other hand are a collection of statements that when called perform an intended action. They are organized and reusable in nature. Functions always return a value.

Now the above example is required when you are within an IDE. If you are running your Python code on the command line, you don’t even need to use print.

# Python 2
$ my-folder: python
Python 2.7.10 (default, Aug 17 2018, 19:45:58)
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 'Hello World'
'Hello World'

# Python 3
$ my-folder: python3
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 03:03:55)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 'Hello World'
'Hello World'

Print by default provides an interface to the standard output(sys.stdout) object. When you use print, you are asking your Python interpreter to echo your message to standard output. For example, you can also print a message, without using print.

# Python 2 and Python 3
import sys

sys.stdout.write('Hello World')
>>> Hello World

You use the write() method in sys.stdout to output your message to the standard output stream.

However, Print is just easier to use.

General Syntax of Print

Let’s look at the general syntax of print in Python.

# Python 2
"print" ([expression ("," expression)* [","]]
        | ">>" expression [("," expression)+ [","]])

# Python 3
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

In both the versions, Python converts the objects into strings(if they are not strings) and then writes to the standard output stream.

Printing multiple elements to the same line

We can use print to write multiple elements in a single line.

# Python 2
print 'Python', 2, 'Rocks'
>>> Python 2 Rocks

# Python 3
print('Python', 3, 'Rocks')
>>> Python 3 Rocks

Print adds a whitespace between each object before writing it to the standard output. In Python 3, you can see a sep argument. It has been set to ' ' by default.

Both the below statements produce the same result.

print('Python', 3, 'Rocks')
>>> Python 3 Rocks

print('Python', 3, 'Rocks', sep=' ')
>>> Python 3 Rocks

The same thing happens with Python 2. However, there is no sep argument in Python 2. White space is added in between objects by default.

You can also pass in a different value to the sep argument in Python 3. For e.g., you could also use `|` as a separator while printing.

print('Python', 3, 'Rocks', sep='|')
>>> Python|3|Rocks

The above can’t be achieved with Python 2 using a print statement. However, you can use the __future__ built-in method in Python 2 to emulate the print function in Python 3.

# Python 2
from __future__ import print_function

print("Python","Rocks", sep="|")

Printing to a newline

Check out this example code.

# Python 2
print 'Python', 2, 'Rocks'
print 'I love Python'
>>> Python 2 Rocks
>>> I love Python

# Python 3
print('Python', 3, 'Rocks')
print('I love Python')
>>> Python 3 Rocks
>>> I love Python

When you have multiple print statements, Python by default prints it to a newline.

In Python 2, a \n character is added to the end whereas, in Python 3, there is an argument end that is set to \n by default.

However, you can change this default behavior.

To print multiple expressions to the same line, you can end the print statement in Python 2 with a comma (,).

You can set the end argument to a whitespace character string to print to the same line in Python 3.

# Python 2
print 'Python', 2, 'Rocks',
print 'I love Python'
>>> Python 2 Rocks I love Python

# Python 3
print('Python', 3, 'Rocks', end=' ')
print('I love Python')
>>> Python 3 Rocks I love Python

With Python 3, you do have the added flexibility of changing the end argument to print on the same line. For e.g.

# Python 3
print('Python', 3, 'Rocks', end='*')
print('I love Python')
>>> Python 3 Rocks*I love Python

In the above example, an asterisk(*) is being used for the end argument.

There is no clean way to do that in Python 2. In order to achieve the above with Python 2, you would have to add the * to the end of every line.

print 'Python', 2, 'Rocks', '*',
print 'I love Python'

Printing to a file

You can also write your message to a file using print in Python. For this purpose,   use the file argument.

# Python 2
print >> open('hello.txt', 'w'), 'Hello World'

# Python 3
print('Hello World', file=open('hello.txt', 'w'))

In the above example, the message is written to a file called hello.txt in the same folder. Notice the use of open() built-in function to save the messages to the file.

If you want to send your messages to any other place other than the standard output, make sure to provide a file object that has a write method to it.

To write to a file in a different folder, provide the full path of the file in your print function.

Flushing in print

This is probably one of the most ignored concepts. Probably because we don’t see any direct impact while we are printing. But it is an important concept.

Usually, Python buffers the messages that you want to print until it gets a newline(\n).

What is Buffer?

A buffer temporarily stores data that is being transmitted from one place to another in the main memory.

The flush argument ensures that everything in the buffer is immediately sent to the destination.

Let’s see this through an example. Instead of the default value for the end argument (\n), we are going to leave it empty.

from time import sleep

print('Will it get printed immediately?', end='')
sleep(5)

When you run the above snippet, the print message will only show up after the 5 seconds of sleep is over. Why? because print expects a \n or a newline at the end of every print statement. Hence, your message is in the buffer.

Using the flush argument, in Python 3, you can directly print the message to the standard output stream without having to wait for the sleep time to finish.

Try this out.

from time import sleep

print('Will it get printed immediately?', end='', flush=True)
sleep(5)

Python Print Examples

Python program to print over the same line

Let's say you have a bunch of print statements.

Code

print("Pylenin")
print("loves")
print("Python")

The output will look like below.

Output

Pylenin
loves
Python

However, if you want to print over and over the same line in Python, you have to use the carriage return \r symbol with the end argument.

Code

print("Pylenin", end="\r")
print("loves", end="\r")
print("Python")

Output

Pythonn

Even though the first 2 print statements are executed, the carriage return makes the next stdout line start at the beginning of the current line.

Also, carriage return will only replace the number of characters contained in the print statement. That is the reason, you have an extra n at the end.


Problems

Qns 1 - Better format a print statement

Print My Name Is Pylenin as My|Name|Is|Pylenin using output formatting of a print() function.

Qns 2 - Print over the same line

Improve the following code so that it prints over the same line.

print("Welcome")
print("to")
print("Python")
print("Bootcamp")
print("2021")

What is the expected outcome?
Solution

Qns 3 - How to print to a file?

Use print statement to print to a file instead of stdout.
Solution

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe