LearnPython.com
  • Courses
  • Articles
  • Log in
  • Create free account
  • fullName

    User profile menu open Open user profile menu avatar
    avatar
    fullName
    Dashboard
    My Profile
    Payment & Billing
    Log out
MENU CLOSE
  • Courses
  • Articles
  • Dashboard
  • My Profile
  • Payment & Billing
  • Log in
  • Create free account
  • Log out 
Back to articles list Articles
25th Jan 2022 6 minutes read

A Complete Guide to the Python print() Function

Author's photo
Luke Hande
  • python
  • python basics
  • print
See More

Let’s explore the Python print() function in detail with some examples. There is more to it than you realize!

There’s a reasonable chance one of your first encounters with Python included print(), possibly in the form of a “Hello, World!” program. The Python print() function is a basic one you can understand and start using very quickly.

But there’s more to it than meets the eye. In this article, we explore this function in detail by explaining how all the arguments work and showing you some examples.

A good reference for how the Python print() function works is in the official documentation. The function accepts several arguments as shown below with their default values:

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

We have touched on the print() function in another article. In the sections below, we’ll go through the arguments one by one and show you everything you need to know to use this function to its full potential. For those of you who are new to Python, take a look at this mini track, which includes interactive coding challenges to accelerate your learning.

*objects

The thing to be printed is represented by the first argument *objects and can be basically anything. It is commonly a string but may be an integer, a float, a variable, a list, or a dictionary, among others. The print() function can also take more than one object.

Since it’s common to print strings, it’s worth mentioning that strings may be defined with either single quotes ('string') or double quotes ("string"). Your personal preference and the use case determine which to use. To demonstrate this, consider the following two examples:

	>>> string = 'She asked "How do you print quotes?"'
	>>> string = "It's about time to program something"

If you’re interested in learning more about working with strings, check out this course. We also have an article where we show you how to index and slice strings.

The most basic use of the Python print() function is for simply printing a string:

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

Unspecified keywords take on their default values, which are listed above in the introduction.

Normal string operations may be used within the function. As an example, you can multiply a string by an integer as shown here:

	>>> print("print this twice " * 2)

At this point, it’s important to touch on string formatting. The old-school way is with %-formatting; however, this isn’t recommended because it gets a little cumbersome with longer strings.

The better way is to use str.format(), where the replacement fields are indicated with curly braces. Let’s define some variables and print them in a string:

	>>> name = "Mary"
	>>> age = 20
	>>> print("{} is {} years old".format(name, age))
Mary is 20 years old

For more examples of string formatting, the official documentation is a good reference. You can also use this method to print tabular data – we have written a separate article on the topic.

Another formatting method is known as f-string formatting. It’s similar to the above example, but it’s a little more compact. Using the same variables from the above, we can write:

	>>> print(f"{name} is {age} years old")
Mary is 20 years old

If you want to print an iterable object like a list or an array, using a starred expression helps unpack the iterable and print it nicely:

	>>> print(*[1, 2, 3, 4])
	1 2 3 4

Try printing the same list without the star and see what you get. Also, try printing the sequence given by the built-in function range() with and without the star. We’ll see some more examples with starred expressions in the next section.

sep

The second argument of the Python print() function defines the separator. If more than one object is given as the first argument, then sep defines what delimiter to place between them. Building on the previous example, we define the separator to be the newline character:

	>>> print(*[1, 2, 3, 4], sep="\n")
	1
	2
	3
	4

Another use case for this argument is for printing some results nicely. We can define a variable and print its value in a human-readable sentence like this:

	>>> result = 10
>>> print("Result of experiment ", result, sep=" is ")
	Result of experiment is 10

Here, the string "Result of experiment" and the variable result both together are the *objects argument, and the value of sep is printed between them.

end

The end keyword allows you to define something to be printed automatically at the end of the output. It defaults to the newline character ("\n").

None of the arguments of the Python print() function are required, strictly speaking. If no arguments are given, the end keyword is printed, which is the newline character by default. It’s pretty straightforward, but for the sake of completeness, let’s build on the previous example by adding an exclamation point at the end:

>>> print("Result of experiment", result, sep=" is ", end="!")
Result of experiment is 10!

file

Not specifying this keyword writes to the terminal in Python by default. The documentation linked above says the default value is sys.stdout, which means “write to standard output” in Python. This is a built-in file object that displays anything written to it (with the .write() method) to the console. If you want to write to a file in Python, specify your own file object with the file keyword.

In anticipation of the final example, let’s define the following string, and save it to the file “flush_demo.py” (don’t worry – this’ll all make sense soon):

	>>> open_file = open('flush_demo.py', 'w')
>>> string = "import time\nfor num in range(10, 0, -1):\n\tprint(str(num)+' ', end='', flush=True)\n\ttime.sleep(1)\nprint('\\nCountdown finished!')"
	>>> print(string, file=open_file)
	>>> open_file.close()

Now, go to your current working directory, and you see the new file we have created. The string is in fact a program, which we’ll use shortly.

It’s important to note you need to define the file object in write mode then close it at the end. If you want more details about writing to file in Python, we have an article covering that.

flush

The flush keyword is a recent addition to the print() function. It accepts a Boolean, either True or False.

Normally, the output to a file or the console is buffered. The buffer is "flushed" (or printed) only when it is full or when a newline is reached. Setting this keyword to True forcibly flushes the buffer before it is full or before a newline character is encountered.

To see this in action, we need to use the file we just created in the previous example. To run this script, open the terminal, navigate to the correct directory, and run:

	>>> python flush_demo.py

You see we have created a countdown clock. With flush=True, the buffer is flushed after every individual number is printed in the loop, then the program sleeps for 1 second. With flush=False, the program sleeps for 10 seconds and the buffer is only flushed at the end of the program, printing the sequence of numbers all at once.

To You, From the Python print() Function

To wrap up this article on the Python print() function, here’s a personalized thank you message. Just copy and paste this into your console:

>>> print(f"Thanks {input('Enter your name: ')}", end=", and Goodbye!")

Tags:

  • python
  • python basics
  • print

You may also like

Python Terms Beginners Should Know – Part 1
Are you new to Python programming? Here's a list of basic Python terms every beginner should know.
Read more
Python Terms Beginners Should Know – Part 2
Are you learning Python but you don't understand all the terms? Get a simple explanation of what common Python terms mean in this article!
Read more
How to Pretty-Print Tables in Python
Whether you want to publish your tabular data online or in an article, Python has some useful libraries to get the job done.
Read more
How to Write to File in Python
Discover how to write to a file in Python using the write() and writelines() methods and the pathlib and csv modules.
Read more
Is it Difficult to Learn Python?
Are you interested in programming but not sure if Python is worth learning? In this article, we dispel your doubts and fears!
Read more
Subscribe to our newsletter Join our monthly newsletter to be notified about the latest posts.

How Do You Write a SELECT Statement in SQL?

What Is a Foreign Key in SQL?

Enumerate and Explain All the Basic Elements of an SQL Query

Quick links

  • Pricing
  • Blog
  • Vertabelo.com

Assistance

Need assistance? Drop us a line at [email protected]

Write to us

Follow us

LearnSQL Facebook We Learn SQL Facebook Linkedin LearnPython.com We Learn SQL Youtube
go to top
Copyright ©2016-2018 Vertabelo SA All rights reserved
Vertabelo
  • Terms of service
  • Privacy policy
  • Imprint