Ultimate Guide to Print() in Python
This article deals with two aspects of the print function. The first is the simple use of python print to the beginner, essentially how do you print in python.
The second part of this article deals with the extensive use of the print function in so many ways and acts as a reference for all of your python print needs.
We use the python print function constantly when we code in python. It is one of the basics for a python beginner, an essential tool for code testing, and used with most python concepts, simply to see the results.
We can add two numbers together using a computer to act like a calculator, such as 2+2, and we expect to see the answer 4. To see this output on the screen we use the print function in the following manner:
print(2 + 2)
We can see the print function uses the key word ‘print’, the brackets that holds the value to print, and the value to print, in this case 2+2
Printing with Arithmetic Operators
We can use the print statement for all of the simple mathematical symbols like addition (+), subtraction (-), multiplication (*) and division (/), seen in the following python print statements:
print(2 + 2)
print(2 - 2)
print(2 * 2)
print(2 / 2)
We have other operators. Have a look at the following print statements and guess what is the output of each.
print(10 ** 3)
print(10 // 3)
print(10 % 3)
The output of these three print statements is 1000, 3 and 1. The first gives the exponential value of the first number to the power of the second number. In this case it is 10*10*10, or ten cubed, or 10 to the power of 3.
If we divide 10 by 3 we get 3 and a third, but we might not want the third so we can use the floor division operator (//) to get the whole number when we divide a number.
The other symbol represents modulus (%) and if we divide ten by three we get nine and one remainder, so we see the output or the result of the operator in the remainder of a division.
Other examples would see the result of 0 for 9%3, 1 for 4%3, and 2 for 20%9.
Printing Numbers in Python
There are two main types of numbers in python, integers and floating point numbers.
It is easier for computers to store and use integers. To print a number in python simply put that number in the print function brackets.
print( 2 )
print( -2 )
print(2000000)
print(0.5)
print(-2.5)
The first three examples are simple integer numbers. The spacing is ignored but included to make it easier for you to see the number.
The final two numbers are floating point numbers. We can write one half as the fraction 0.5, and we can also include negative numbers.
We can see what type a number is by using the type() function inside the print function. We put the number inside the brackets of the type function.
print( type( 2 ) )
print( type( 2.0 ) )
The first example prints ‘int’ for integer and the second prints ‘float’ to represent the floating point number. Notice the addition of the decimal point makes 2.0 a floating point number in python.
Printing Data Types in Python
We have seen both integers and floating point numbers, otherwise called floats in python. but what if we what to print our name or even a digit that is not a number (e.g. phone numbers)?
We can use either single quotation marks or double quotation marks, around the value to be printed, to tell python the value is a string. The following are all strings:
print( 'hello' )
print( "hello" )
print(' ')
print("999")
print("...")
It is useful to be able to use either single or double quotations and necessary if the string value contains one of those characters.
Notice in the following print statements the strings include quotation mark characters.
print( " he can't " )
print( 'she said "hello all" to us')
phone users can slide left to see all of the code
Another type of data, or data type, is a Boolean. A Boolean has either a value of true or false.
Imagine we have something called ‘bol’ and this has the value of either true or false. This is how we can print it.
bol = True
print(bol)
Output: True
bol = False
print(bol)
Output: False
The first will print ‘True’ and the second will print ‘False’ as you would expect.
The idea of giving a value a name is something we see when we use variables, which we will see very shortly.
The logic of true or false is important in python. We can check to see if something is true or false in the print statement. The following examples will print true:
print(2 > 1)
print(5 <= 6)
print(7 == 7)
print(5 != 6)
print(1 + 1 == 2)
To determine if two numbers are the same we use the comparison operator == rather than one equals sign. To determine if two numbers are not the same we use the != comparison operator.
What would you do if you wanted to print the actual characters to the screen rather than check if they were true or not?
To change these to strings just add quotation marks. Here are the print statements containing the characters in strings, and the outputs:
print("2 > 1")
Output: 2 > 1
print('7==7')
7==7
Output: 7==7
Printing Variables in Python
We can print variables using the print function in the same manner as the data types we have seen previously although we do not use quotation marks.
If a variable has a value (initialized) then when we put the variable name in the print function brackets it will print the value.
For example, the following variable name is given the value ‘John Smith’, which is seen in the output when name is printed.
name = “John Smith”
print(name)
Output: John Smith
This is the same for printing variables with values that are integers, floating point numbers or a Boolean.
age= 21
print(age)
Output: 21
price= 9.50
print(price)
Output: 9.50
easy= True
print(easy)
Output: True
We can perform simple operations on variables and see the expected output of these calculations using variables, for example:
age = 21
print(age + 1)
Output: 22
An interesting question is how to make a variable empty or to ‘clear’ a variable. If you wish to make a variable have no value then there are two options.
If you want the variable to not exist, which will cause an error message if you try to use it, you can use the del option.
Or, if you want the variable to exist then you can use the None option. Here are some examples.
name = 'Codie'
print(name)
Output: Codie
name = None
print(name)
Output: None
name = 'Codie'
del name
print(name)
Output: NameError: name ‘name’ is not defined
Type Conversion in Python Print
Something that is different in python than other programming languages is the use of data types without saying (explicitly) what type they are. Python can ‘guess’ what the type is, or even change it.
For example, both 5 and 2 are integers, but five divided by two results in the floating point numbers 2.5. Python will automatically change the type, seen in the following example:
x = 5
x = x/2
print(x)
Output: 2.5
print(type(x))
Output: float()
It is possible to change the data type yourself by using the functions int() that changes a value to an integer, if possible, float() and str(). Here are examples:
print("string: ", str(10))
print("int: ", int("10"))
print("float: ", float("10"))
With the following output:
Output:
string: 10
int: 10
float: 10.0
It is important to know which type that a variable is otherwise your code may act in a different manner than you want and ultimately cause problems and errors, some that python won’t find for you.
An example of the actions differing for the data types is the use of the addition (+) operator, which can concatenate (like add) strings together, and the multiply (*) operator that can multiply strings.
We see the different outputs for the different data types although the code is very similar. Some result in error messages.
x = 5
print(x + 2)
Output: 7
x = '5'
print(x + 2)
Output: TypeError: can only concatenate str (not “int”) to str
x = 5
print(x * 3)
Output: 15
x = '5'
print(x * 3)
Output: 555
User Input and Print in Python
So far we have set the values of the variables in the code but sometimes we want values from outside of the code, for example, from the user.
We need to provide a message to help the user know what and when to enter something, like: message = “please enter a number”
To get the reply we use ‘input’ and put the message inside the brackets.
x = input(message)
print(x)
The strange thing about input is the input from the user is always created as a string, even when a number is entered. This example shows the type string is given although the user enters an integer.
message = “please enter a number”
x = input(message)
print(type(x))
Output: str()
What happens if you want an integer not a string? The solution to this problem is changing the type. Remember the last section we showed how to change the data type of a variable.
message = “please enter a number”
x = input(message)
x = int(x)
print(type(x))
Output: int()
If you are not sure of the number it can be safer to change the string to a float.
message = “please enter a number”
x = input(message)
x = float(x)
print(type(x))
Output: float()
Printing Strings in Python
There are many string functions that we can demonstrate but we focus here on how we can print a string, such as “Hello”, in different ways.
For example, we can amend the case of a string to uppercase, to lowercase or even to capitalize:
print("Hello".lower())
print("Hello".upper())
print("hello".capitalize())
Another useful string function is strip() that we use when we get a string from input.There are cases when we have unwanted characters, such as spaces, from extracted text, such as with web pages and html.
print(x.lstrip())
print(x.rstrip())
print(x.strip())
We have the variable x, which is a string, and we can apply the strip function to remove unwanted characters from both sides of the relevant characters.
If we wish to focus on the characters before our wanted text, to the left, we can use left strip, lstrip(). We also have right side strip, rstrip().
Printing Loops in Python
There are two types of loops: while loops and for loops.
The while loop will repeat the following code forever unless it has a way of stopping. The for loop repeats for a given amount of times (called iterations). Here are examples that print numbers 1 to 10.
for i in [1,2,3,4,5,6,7,8,9,10]:
print(i)
for i in range(1,10):
print(i)
i=1
while i < 11:
print(i)
i = i + 1
The for loop can also print letters or characters in a string:
for letter in "hello coder":
print(letter)
The output would be each character on a new line, starting from the letter h, then e, to o, then a space, then c to r.
Printing with Range in Python
The index of a list can be used to iterate through each item, this is good to know if you need to use the index in some form. In the for loop we use the range() function.
The range function begins at 0 and therefore is perfect for use with lists. Here is an example where we print the index and the value using the range function:
alist = ['a', 'b', 'c', 'd', 'e']
for i in range(5):
print( i, alist[i] )
Output:
0 a
1 b
2 c
3 d
4 e
If you have a list that may change then the range function should use the length function len() instead of the static number. For example, the code above could have for i in range(len(alist)).
In addition, if you need the values with a counter it is suggested you can use enumerate. To produce the same output as seen in the last example we can use the following code:
alist = ['a', 'b', 'c', 'd', 'e']
for x, y in enumerate(alist):
print (x, y)
Output:
0 a
1 b
2 c
3 d
4 e
2 -Print Format
There are ways we can tell python exactly how we want to format the output of a string or a number, such as the number of decimal places, or to format a line of text and space before another value.
There are options to use the formatting available in python, and this has also changed. We can see an example using the f syntax:
st = "Sai"
score = 88
print(f"student {st}: {score}")
Output: student Sai: 88
It is also possible to use format for numbers. An example is when you wish to reduce the amount of decimal places.
mypi = 3.1415926536
mypi2 = "{:.2f}".format(mypi)
print(mypi2)
Output: 3.14
Spacing and Print in Python
We can print in different formats in python as we will se in detail later, but some simple print statements include the following:
print("int: ", 5)
print("float: ", 2.5)
print("string: ", 'seven')
The use of the comma will results in a space between the values, giving the following output to the print statements above:
Output:
int: 5
float: 2.5
string: seven
We can print spaces within strings and also as strings. in the following examples the print function is followed by the output.
The final example uses the * operator to multiple the string of one space (‘ ‘ * 3 ) to produce three spaces:
print("part one")
print('bigger gap')
print('x',' ','x')
Output:
part one
bigger gap
x x
print('x',' '*3,'x')
Output: x x
There are several methods to print using spacing, tabs, and new lines. Here are some examples:
#prints an empty line
print()
#prints hello coder
print("hello","coder")
#prints hellocoder
print("hellocoder")
#prints hellocoder
print("hello" + "coder")
#prints hello coder
print("hello","\t","coder")
# - prints hello
#coder
print("hello","\n","coder")
The “\t” symbol represents a tab, whilst “\n” is used for a new line.
Print Separators in Python
We can use different characters to separate strings, such as commas, spaces or other characters. Here are some examples:
print("hello","world","repeats","world",sep=",")
print("hello","world","repeats","world",sep="")
print("hello","world","repeats","world",sep=" ")
print("hello","world","repeats","world",sep="/")
print("hello","world","repeats","world",sep="\n")
hello,world,repeats,world
helloworldrepeatsworld
hello world repeats world
hello/world/repeats/world
hello
world
repeats
world
We use the separator when we want to join list elements to form one string using the join function. The separator joins each value such that it is in between each item. Let’s make a string with list elements separated by commas:
x = ['a', 'b', 'c', 'd']
separator = ','
print(separator.join(x))
print()
Output: a,b,c,d
There are also separators that can be used to make numbers easier to read, such as commas in larger numbers to see millions and thousands.
x = 1000000
print( f"{ x:,}" )
Output: 1,000,000
Print Same Line in Python
Loops print values on a new line, if you want to print on the same line you can use ‘end’. Making end equal nothing (“”) overrides the newline default. Here is an example:
for i in 'name':
print(i)
Output:
n
a
m
e
for i in 'name':
print(i, end="")
Output: name
3 - Print Function Explained
In the last two examples we have seen the use of sep for separator, and end. Why are these important to understand how print works as a function?
When we have two items in the parenthesis in a print function, separated by a comma, or multiple items, again separated by commas, then python knows to print these with a space between then, in order.
In a loop we print each item on a new line, so each item is printed and followed by a new line. So the items that are printed in a print function are function parameters, they are printed in order.
There are also these default values that we don’t see, such as a space for sep and a newline for end. We see these named parameters in the documentation for the python function.
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
The first parameter takes all the items in the print function and treats them like a string and prints them, in order, to the standard output, such as your monitor screen.
Next we have already seen both the separator parameter called sep, and the end parameter. The words sep, end, file and flush in the print function are called keyword arguments.
We also have file and flush, file is used to print to a file with write() that changes the sys.stdout, which is the output to your screen. Flush can be changed from the default value of False, to True, when the output is flushed, or outputted immediately without being buffered.
Here is an example of the print function using file:
filename = open('example.txt', 'w')
print('hello coder', file = filename)
filename.close()
Although we prefer to use ‘with’ when opening files as python will do the cleaning up management automatically for you, so is better python code:
with open(filename, 'w') as fn:
print('hello coder', file=fn)
To see flush we need to have some data in the buffer. A buffer is a place in memory that is waiting to be used, like the next part of a movie that is being streamed and waiting to be watched.
In this example, the first code snippet will print after the 3 seconds as the print statement is expecting a newline to be used from the buffer.
from time import sleep
print('This will wait', end='')
sleep(3)
The second example prints the message without waiting as the flush with a True value forces the output immediately.
from time import sleep
print('This will wait', end='',flush='True')
sleep(3)
4 - Printing Python Data Structures
There are several data structures in python such as sits that we have seen already, sets, tuples and dictionaries. these can be printed in their entirety but it is also common to iterate through their values using the print function.
The use of different brackets determines which data structure is used to hold a series of values. Here are examples:
print("list: ",[1,2,3,4,3,2,1])
print("set: ",{2,4,6})
print("tuple: ",(2,2,4,6,6))
print("dictionary: ",{1:"a",7:"d",4:"z"})
Output:
list: [1, 2, 3, 4, 3, 2, 1]
set: {2, 4, 6}tuple: (2, 2, 4, 6, 6)
dictionary: {1: 'a', 7: 'd', 4: 'z'}
These print the whole data structure. If you wish to print each value within the data structure then you can use a for loop, such as the following:
#example data structures
alist = [8, 6, 3, 9, 8]
aset = {2, 4, 6}
atuple = ('a', 'c', 'd')
adict = {1:'a', 7:'d', 4:'z'}
for i in alist:
print(i)
Output:
8
6
3
9
8
for i in aset:
print(i)
Output:
2
4
6
for i in atuple:
print(i)
Output:
a
c
d
for i in adict.items():
print(i)
Output:
(1, ‘a’)
(7, ‘d’)
(4, ‘z’)
If you wish to print these in order the we can add the sort() function.
Printing a list in Python
There are several approaches to printing a list, an element from a list, or a sliced part of a list. Here is a list of ways a list, a part of a list, or an amended list, can be printed:.
alist = ['C', 'r', 'o', 'i', 'D']
#print a list
print(alist)
#print the length of a list
print(len(alist))
#print a list using a for loop
for i in alist:
print (i)
#print the first element in a list
print(alist[0])
#print the last element in a list
print(alist[-1])
#print a list using the length of the list and the index
for i in range(len(alist)):
print(i,alist[i])
#check if a value is in a list, or not in a list
if 'r' in alist:
print('found')
if 'r' not in alist:
print('not found')
#check if a value is in a list and print the index
i = alist.index('r')
print('index is:', i)
#check if a value is in a list and print the indexes
x = [i for i,j in enumerate(alist) if j=='r']
print(x)
#increase a list using the + operator, append or extend
multiply a list
x = alist + alist
print(x)
alist.append('a')
print(alist)
alist.extend(['a','b'])
print(alist)
alist = alist*2
print(alist)
#print a sorted list
alist.sort()
print(alist)
#print a slice of a list from the front
x = alist[:3]
print(x)
#print a slice of a list at the back
y = alist[1:]
print(y)
#print a string as a list by conversion
x = list(s)
print(x)
#print a string as a list using split()
x = s.split()
print(x)
Printing a dictionary in Python
We can print a dictionary either as the whole dictionary or using the items as follows:
print("dictionary: ",{1:"a",7:"d",4:"z"})
Output: dictionary: {1: ‘a’, 7: ‘d’, 4: ‘z’}
adict={1:'a', 7:'d', 4:'z'}
for i in adict.items():
print(i)
Output:
(1, ‘a’)
(7, ‘d’)
(4, ‘z’)
There are other ways to access the key or the value from a dictionary. Using the above dictionary we can print the keys and the values with the following for loops:
for i in adict.keys():
print(i)
Output:
1
7
4
for i in adict.values():
print(i)
Output:
a
d
z
To change the order of the keys or values of the dictionary it is possible to use a sorted function and a reverse function. Here is a series of ways to print a dictionary:
adict= {1:'a', 7:'d', 4:'z'}
#reversed
rdict = dict(reversed(list(adict.items())))
for k,v in rdict.items():
print(k,v)
Output:
4 z
7 d
1 a
#ordered by keys
for k in sorted(adict.keys()):
print(k)
Output:
1
4
7
#ordered by values
for v in sorted(adict.values()):
print(v)
Output:
a
d
z
#ordered
sdict = dict(sorted(adict.items()))
for k,v in sdict.items():
print(k,v)
Output:
1 a
4 d
7 d
#ordered in reverse by key
for i in sorted(adict.keys(), reverse=True):
print (i,adict[i])
Output:
7 d
4 z
1 a
#ordered by value
for k in sorted(adict, key=adict.get):
print(k, adict[k])
Output:
1 a
7 d
4 z
#ordered in reverse by value
for k in sorted(adict, key=adict.get, reverse=True):
print(k, adict[k])
Output:
4 z
7 d
1 a
5 - Further Print Examples
Print and Path in Python
We can print files and folders using the os library. In this example we import os, then use it to see the current working directory (CWD):
import os
print(os.path.abspath(os.getcwd()))
Print and Time in Python
We might use time to calculate the amount of time that a program runs but also as a delay mechanism inside our code.
Imagine if we want a clock and to delay printing the time by one second whilst the clock increased by a second on each print action.
We import the time library and can use several functions such as sleep().
import time
print(1)
time.sleep(1)
print(2)
Print Color in Python
R = '\033[31m' # red
print(R+"hello")
B = '\033[30m' #black
print(B+"hello")
Output:
hello
hello
Print Audio in Python
import winsound
frequency = 2500 # Set Frequency To 2500 Hertz
duration = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(frequency, duration)
As you may have noticed, this page is under construction. Unfortunately putting code into a webpage has issues and we are currently experimenting with ways we can do this and still make the article readable.
Please be patient, we are improving it regularly. If there is anything that you would like added, changed or explained better then please let us know.
Further information
For further information on special formatting using print in python see the documentation at https://docs.python.org/3/tutorial/inputoutput.html
There is also further information on formatting and strings available at https://flexiple.com/python-print-variable/, or formatting and numbers at https://blog.teclado.com/python-formatting-numbers-for-printing/.
The % operator was used for string substitution previously, but now format is the preferred method of use in python for formatting. But if you need to understand the use of % during formatting see https://stackoverflow.com/questions/20450531/python-operator-in-print-statement.
6 - Print Function FAQ
There are common questions asked about how to print something in python. Here is a range of frequently asked questions with solutions and example python code.
How do you print the current python version?
To print the current version of python installed on a device install sys and print sys.version.
import sys
print (sys.version)
How do you print on the same line?
To print on the same line use end=””, this removes the default newline end that makes print use a new line.
for i in 'name':
print(i, end="")
Output: name
How do you print a new line?
To print a new line use the “\n” newline escape sequence, this will print a new line.
print("\n")
If you wish to print an empty line then just type print() and leave the brackets empty.
How do you print a string backwards?
There is no built-in string function that reverses a string, but it is possible to use the range option with a -1 step.
name = "Dr Codie"[::-1]
print(name)
Output: eidoC rD
How do you print a list backwards?
There is a built in list function that reverses the elements inside a list called .reverse(). Call this function on your list and the list elements will appear in the reverse order when the list is printed.
alist = ['C', 'r', 'o', 'i', 'D']
alist.reverse()
print(alist)
Output: [‘D’, ‘i’, ‘o’, ‘r’, ‘C’]
How do you print a number to two decimal places?
To print a number to decimal places use format with 2f stated inside the curly brackets.
mypi = 3.1415926
mypi2 = "{:.2f}".format(mypi)
print(mypi2)
Output: 3.14