Python print() Function

Python print function

There are several key functions in the Python programming language that are super useful. The Python print function is definitely one of the first ones that you should know. The print function accepts data as an input and then displays that data to the screen for the user to view. The print() function will be used all the time since it allows you to output the contents of a variable to the screen, allowing you to understand how your program is processing data. Let’s look at some examples of using the Python print function now.


Printing A Message

The first example of print() is to simply output a message to the screen. First, we’ll need a message variable so that we can print out that variable and see what the content of the message is. So here we initialize a message variable and we Simply put the string ‘Well hello there!’ inside the variable. The message can be a string or any other object, it will be converted into a string before being written to the screen.

# initialize a message
message = 'Well hello there!'

To display the message on the screen, we would call the print function and pass and message as input like this:

print(message)
Well hello there!

Printing A Sentence

Next, let’s say that I have a variable named ‘message1’ containing the string ‘Howdy’, a variable named ‘name1’ containing the string ‘Tom’, a variable named ‘message2’ containing the string ‘Hello’, a variable named ‘name2’ containing the string ‘Ben’, and a variable named ‘punctuation’ containing some exclamation marks as a string. We can form sentences using these variables and display them on the screen by calling the print() function and passing in these variables as inputs like this:

# initialize message1
message1 = 'Howdy'

# initialize name1
name1 = 'Tom'

# initialize message2
message2 = 'Hello'

# initialize name2
name2 = 'Ben'

# initialize punctuation
punctuation = '!!!'
print(message1, name1, punctuation)

print(message2, name2, punctuation)
Howdy Tom !!!
Hello Ben !!!

Printing Iterables

Another thing that we can do with the print function is to print out iterables to the screen. First, let’s initialize a list of even numbers with the ‘even_nums’ variable. With that list initialized we can then pass that as input to the print() function and see the result on the screen.

# initialize even_nums as a list containing some even integers

even_nums = [-2, -8, -4, 6, 10, 12]

print(even_nums)
[-2, -8, -4, 6, 10, 12]

You may not want to print the iterable to the screen in one shot. That is the whole point of an iterable, we would like to be able to iterate over the values. In this next example we can use the same list but loop over it and print out each individual item one at a time:

even_nums = [-2, -8, -4, 6, 10, 12]
for num in even_nums:
    print(num)
-2
-8
-4
6
10
12

Printing A Slope

In this example, we have a tuple containing the variables x1 and y1, and this tuple will represent the point 7 and 12 on a line. We have a second tuple containing variables x2 and y2 and this tuple represents the point -5, -9 on the same line. To compute the slope of the line using the two points and display the slope with a label on the screen, we can call the print() function while passing in ‘slope:’, and an arithmetic expression involving the two points as inputs like this.

# initialize a point on a line
(x1, y1) = (7, 12)

# initialize another point on the same line
(x2, y2) = (-5, -9)

# compute the slope of line using the two points & display with label
print('slope:', (y2 - y1) / (x2 - x1))
slope: 1.75

Printing Pandas Data

This next example will be just slightly more advanced. We can use the popular Pandas library in Python to read a CSV file into a pandas dataframe and then print out various pieces of information in that data frame let’s see a few examples of that here. To use the Pandas library in Python we first have to import it. We can import it using this code here. Note that we are using an alias to make it easier to work with the library instead of needing to type out pandas we can simply type pd with this approach.

import pandas as pd

Using pandas, we can read in a dataset from a CSV file, which is stored as a data frame in the ‘stocks’ variable.

# read a stocks dataset then save as a pandas dataframe
stocks = pd.read_csv('stocks.csv')

Now we get to use our handy print() function once again. Here, we call the print function passing in the first 5 rows of the dataframe.

# display first five rows of stocks
print(stocks.iloc[:5])
       stock ticker    price
0      Apple   AAPL   114.38
1     Google   GOOG  1723.73
2  Microsoft   MSFT   208.62
3    Qualcom   QCOM   142.71
4      Tesla   TSLA   518.46

In this next piece of code, we can check for missing values in the price column of our data set. If any of those values are missing then we can simply print() there are missing prices, otherwise, we just print() there are no missing prices.

# check for missing values in the price column
if stocks['price'].isnull().values.any():
    print('There are missing prices')
else:
    print('There are no missing prices')
There are no missing prices

The last example of using the print() function with our pandas dataframe will involve checking for the stocks that have a price of over 100 and also for the stocks that have a price below 100.

price_over_100 = stocks.loc[stocks['price'] >= 100]['price'].values
price_below_100 = stocks.loc[stocks['price'] < 100]['price'].values
print('price at least 100:', price_over_100)
print('price below 100:', price_below_100)
price at least 100: [ 114.38 1723.73  208.62  142.71  518.46  262.97  514.03]
price below 100: [58.93 13.43]

Print Parameter Values

print(object(s), sep=separator, end=end, file=file, flush=flush)
Parameter Description
object(s) This can be one or more objects. Converted to string before printing
sep=’separator Optionally specify how to separate the objects, if there is more than one. Default is ‘ ‘
end=’end Optionally specify what to print at the end. Default is ‘\n’ (new line)
file Optional. An object with a write method. Default is sys.stdout
flush Optional and specifes if the output is flushed (True) or buffered (False). Default is False

Python print() Function Summary

The print() function is useful for so many applications. As you program applications in Python, you’ll also find yourself inserting print() calls into the code at strategic points in order to display the values of different variables at different times.