print in Python: displaying messages on screen
Hey there! In this article, we’ll talk about the print function in Python. This function is handy for showing messages on the screen or saving them in a file. We’ll discuss how to utilize this function in depth, along with its differences in Python 3 compared to Python 2.
Displaying messages on screen in Python 3
To show a message on the screen in Python 3, you can use the built-in print function:
print("Hello, world!")Output:
Hello, world!Displaying messages on screen in Python 2
In Python 2, you use the print keyword, not the function:
print "Hello, world!"Output:
Hello, world!For the rest of the article, we’ll focus mainly on the print function in Python 3. If you’re curious about print in Python 2, I’d recommend checking out the official documentation.
The print function
The print function in Python looks like this:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)- First, we pass the objects we want to display. The
printfunction will automatically turn these into strings. The asterisk indicates that we can pass any number of values. - By default, all values are shown separated by a space. To change the separator, use
sep='your separator'. - After all the objects are displayed,
printwill move to the next line. You can adjust what’s shown at the end by using theendargument. - By default, the message will show on the screen. But, if you want to direct it to a file, use the
fileargument. flushdetermines whether the message appears right after calling the function or if it waits a bit. Messages usually aren’t shown immediately after calling because programs run faster that way. If you want to ensure the message appears immediately after usingprint, setflush=True.
Now, let’s see how each of these arguments works individually.
Displaying multiple values
print lets you show multiple values in one message:
print("I", "went", "for a walk")Output:
I went for a walkAnd we’re not limited to just strings:
print("2 * 3 =", 6)Output:
2 * 3 = 6The print function will convert any value you give it into a string. Let’s try showing the print function using print itself:
print('print:', print)Output:
print: <built-in function print>Here, we see that print is a built-in function in Python.
How to change the separator in print
To change the space with something else when printing multiple values, you can use the sep parameter:
print(1, 2, 3, sep=", ")Output:
1, 2, 3Here, we’ve displayed numbers separated by a comma and a space. You can choose any separator that fits your needs.
How to change the print ending
By default, print starts a new line after each print statement:
print("First line")
print("Second line")Output:
First line
Second lineYou can adjust what gets printed at the end of a message by using the end argument:
print("One |", "Two", end=" | ")
print("Three")Output:
One | Two | ThreeWriting messages to a file
To write a message to a file, print has a special parameter named file. Let’s try printing the message “Hello World!” to a file called output.txt:
with open("output.txt", "w") as f:
print("Hello World!", file=f)output.txt:
Hello World!In the example above, we’re using the open function to open a file for writing. Once the file is opened, you just pass it to the file parameter of the print function.
Flushing the print output with flush
Before we jump into flushing the print output, let’s demonstrate the fact that messages don’t always show up on the screen immediately:
import time
print("Message #1", end=", ")
time.sleep(3)
print("message #2")I’d recommend running this code on your computer to see it in action. But in any case, here’s what’ll happen:
- For the first three seconds, you won’t see anything on the screen, even though
printhas been called. - After three seconds, the second call to
printwill flush the waiting output to the screen.
You’ll end up seeing:
Message #1, message #2To see the first message right away, without waiting for the second print, you can set flush=True. This will prompt Python to display “Message #1, ” without waiting for the next print call:
import time
print("Message #1", end=", ", flush=True)
time.sleep(3)
print("message #2")By default, Python displays a message on screen after a newline character
'\n'. That’s why, to demonstrate theflushparameter, we changed theendfor the first message to a comma.
Example: printing an integer
As we’ve seen, to print numbers using the print function, you can simply pass the number:
number = 1
print(number, 2)Output:
1 2Example: displaying a string on the screen
You can easily pass a string as a parameter to the print function to display it:
print("Displaying a string in Python")Output:
Displaying a string in PythonExample: displaying a list in Python
To display a list, you can simply pass it to the function. In this case, print will show the list items separated by commas within square brackets:
l = [1, "two", 3]
print(l)Output:
[1, 'two', 3]If you need to display the items differently, you can do it manually:
l = [1, "two", 3]
for index, item in enumerate(l):
print(item, end="")
if index == len(l) - 1:
print() # new line
else:
print(" | ", end="") # custom delimiterOutput:
1 | two | 3But the example above is a bit verbose. It’s easier to use the join method:
l = [1, "two", 3]
print(" | ".join(str(x) for x in l))Output:
1 | two | 3Here, we first converted all list elements to strings using a generator and then joined them using join.
Example: displaying a dictionary using print
The print function can also beautifully display dictionaries:
d = {"A": 1, "B": 2}
print("Dictionary:", d)Output:
Dictionary: {'A': 1, 'B': 2}Example: displaying a set in Python
You can also display sets using the print function:
s = {1, 2, 3}
print("Set:", s)Output:
Set: {1, 2, 3}Exercises
- Using
print:
Write a Python program that asks the user for their name and displays a welcome message on the screen using theprintfunction. - Writing to a file using
print:
Create a text file named “output.txt”. Write a program that uses theprintfunction to write the string “Hello, world!” to this file. After executing the program, open the file to ensure the string was written correctly. - Managing delimiters and line endings in
print:
Write a program that showcases the ability to use various delimiters and line-ending characters in theprintfunction. Try changing the default delimiter (space) and default line ending (new line) to something else, and display multiple values on the screen.
Discussion