print()

The built-in print() function lets you display text or other data to the standard output or another output stream. By default, the output is displayed on the screen, but it can be redirected to a file or other output stream:

Python
>>> print("Hello, World!")
Hello, World!
Python Syntax
print(*objects, sep=" ", end="\n", file=None, flush=False)

Arguments

Argument Description Default Value
*objects An arbitrary number of Python objects to be displayed end
sep The string used to separate the objects " " (space)
end The string appended after the last object "\n" (newline)
file The file-like object where the output is sent sys.stdout
flush A Boolean value that specifies whether to forcibly flush the output buffer False

Return Value

  • The print() function returns None.
  • It performs an output operation as a side effect, displaying or writing the input objects.

With a single string argument:

Python
>>> print("Hello, Real Python!")
Hello, Real Python!

With multiple arguments and a custom separator:

Python
>>> print("Python", "is", "fun", sep=" - ")
Python - is - fun

Redirecting output to a file rather than to sys.stdout:

Python
>>> with open("output.txt", "w") as file:
...     print("Hello, file!", file=file)

The most common use cases for the print() function include:

  • Displaying messages or results to the user
  • Debugging by showing variable values or program states
  • Logging information to a file
  • Creating simple text-based user interfaces (TUI)

Create a simple progress bar for a command-line interface using the print() function. This progress bar will visually indicate the completion percentage of a task:

Python
def progress(percent=0, width=30):
    end = "" if percent < 100 else "\n"
    left = width * percent // 100
    right = width - left
    print(
        "\r[",
        "#" * left,
        " " * right,
        "]",
        f" {percent:.0f}%",
        sep="",
        end=end,
        flush=True,
    )

# Usage
from time import sleep

for percent in range(101):
    sleep(0.1)
    progress(percent)

# Output: [###########                   ] 38%

This code will display a progress bar that updates in place as the task progresses. The flush=True ensures that each update is immediately shown on the screen.

Tutorial

Your Guide to the Python print() Function

In this step-by-step tutorial, you'll learn about the print() function in Python and discover some of its lesser-known features. Avoid common mistakes, take your "hello world" to the next level, and know when to use a better alternative.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 14, 2024 • Reviewed by Dan Bader